返回
剑指Offer05:js/ms15 逆向输出单链表
前端
2024-01-29 12:02:44
前言
单链表是一种常用的数据结构,它由一组节点组成,每个节点包含一个数据项和一个指向下一个节点的指针。逆向输出单链表是指将单链表中的元素从后往前输出。这在某些场景下非常有用,例如调试代码或查找链表中的特定元素。
递归解法
递归是一种将问题分解成更小的子问题,然后重复解决这些子问题直到达到基本情况的编程技术。它非常适合于解决单链表逆向输出问题。
算法步骤
- 定义一个递归函数
reverseList()
,该函数接收一个头节点head
作为参数,并返回一个新的头节点,该头节点指向反转后的链表。 - 如果
head
为null
或head.next
为null
,则直接返回head
。 - 否则,调用
reverseList()
函数递归地反转head.next
部分的链表,并将其返回。 - 将
head.next
指向head
。 - 将
head
指向反转后的链表。 - 返回反转后的链表的头节点。
代码示例
/*
* 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)原则的数据结构。它非常适合于解决单链表逆向输出问题。
算法步骤
- 创建一个栈。
- 将单链表中的元素逐个压入栈中。
- 从栈中弹出元素,并将它们输出。
代码示例
/*
* 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来逆向输出单链表的解决方案:递归和栈。我们还分析了这两种解法的時間复杂度。希望這篇文章对您有所帮助。