返回

剑指Offer05:js/ms15 逆向输出单链表

前端

前言

单链表是一种常用的数据结构,它由一组节点组成,每个节点包含一个数据项和一个指向下一个节点的指针。逆向输出单链表是指将单链表中的元素从后往前输出。这在某些场景下非常有用,例如调试代码或查找链表中的特定元素。

递归解法

递归是一种将问题分解成更小的子问题,然后重复解决这些子问题直到达到基本情况的编程技术。它非常适合于解决单链表逆向输出问题。

算法步骤

  1. 定义一个递归函数reverseList(),该函数接收一个头节点head作为参数,并返回一个新的头节点,该头节点指向反转后的链表。
  2. 如果headnullhead.nextnull,则直接返回head
  3. 否则,调用reverseList()函数递归地反转head.next部分的链表,并将其返回。
  4. head.next指向head
  5. head指向反转后的链表。
  6. 返回反转后的链表的头节点。

代码示例

/*
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */

/**
 * Given the head of a singly linked list, reverse the list, and return the new head.
 *
 * @param {ListNode} head
 * @return {ListNode}
 */
const reverseList = (head) => {
  if (head === null || head.next === null) {
    return head;
  }

  const newHead = reverseList(head.next);
  head.next.next = head;
  head.next = null;

  return newHead;
};
# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def reverseList(head):
    if head is None or head.next is None:
        return head

    new_head = reverseList(head.next)
    head.next.next = head
    head.next = None

    return new_head

栈解法

栈是一种遵循后进先出(LIFO)原则的数据结构。它非常适合于解决单链表逆向输出问题。

算法步骤

  1. 创建一个栈。
  2. 将单链表中的元素逐个压入栈中。
  3. 从栈中弹出元素,并将它们输出。

代码示例

/*
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */

/**
 * Given the head of a singly linked list, reverse the list, and return the new head.
 *
 * @param {ListNode} head
 * @return {ListNode}
 */
const reverseList = (head) => {
  const stack = [];

  while (head !== null) {
    stack.push(head);
    head = head.next;
  }

  let newHead = null;
  let current = null;

  while (stack.length > 0) {
    const node = stack.pop();

    if (newHead === null) {
      newHead = node;
    } else {
      current.next = node;
    }

    current = node;
  }

  current.next = null;

  return newHead;
};
# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def reverseList(head):
    stack = []

    while head is not None:
        stack.append(head)
        head = head.next

    new_head = None
    current = None

    while len(stack) > 0:
        node = stack.pop()

        if new_head is None:
            new_head = node
        else:
            current.next = node

        current = node

    current.next = None

    return new_head

时间复杂度

这两种解法的時間复杂度均為 O(n),其中 n 为链表中的元素个数。

結論

在本文中,我们介绍了两种使用JavaScript和Python来逆向输出单链表的解决方案:递归和栈。我们还分析了这两种解法的時間复杂度。希望這篇文章对您有所帮助。