剑指 Offer 24. 反转链表
写在前面
小编在刷题的时候发现理解递归的详细过程是一件很难的事情,脑袋就像是一团浆糊,总是有大大的问号?直到跟着PyCharm调试一下才大致明白详细的逻辑,所以后面附上详细的PyCharm运行程序供小伙伴调试理解。
题目描述
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
限制:0 <= 节点个数 <= 5000
题目解析
如下图所示,题目要求将链表反转。本文介绍迭代(双指针)、递归两种实现方法。
方法一:迭代(双指针)
考虑遍历链表,并在访问各节点时修改 next
引用指向,算法流程见注释。
复杂度分析:
- 时间复杂度
O(N)
: 遍历链表使用线性大小时间。 - 空间复杂度
O(1)
: 变量pre
和cur
使用常数大小额外空间。
Python代码
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
cur, pre = head, None
while cur:
tmp = cur.next # 暂存后继节点 cur.next
cur.next = pre # 修改 next 引用指向
pre = cur # pre 暂存 cur
cur = tmp # cur 访问下一节点
return pre
利用 Python 语言的平行赋值语法,可以进一步简化代码(但可读性下降):
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
cur, pre = head, None
while cur:
cur.next, pre, cur = pre, cur, cur.next
return pre
方法二:递归
考虑使用递归法遍历链表,当越过尾节点后终止递归,在回溯时修改各节点的 next
引用指向。
recur(cur, pre)
递归函数:
- 终止条件:当
cur
为空,则返回尾节点pre
(即反转链表的头节点); - 递归后继节点,记录返回值(即反转链表的头节点)为
re
; - 修改当前节点
cur
引用指向前驱节点pre
; - 返回反转链表的头节点
res
;
reverseList(head)
函数:
调用并返回recur(head, null)
。传入null
是因为反转链表后,head
节点指向null
;
复杂度分析:
- 时间复杂度
O(N)
: 遍历链表使用线性大小时间。 - 空间复杂度
O(N)
: 遍历链表的递归深度达到N
,系统使用O(N)
大小额外空间。
Python代码
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
def recur(cur, pre):
if not cur: return pre # 终止条件
res = recur(cur.next, cur) # 递归后继节点
cur.next = pre # 修改节点引用指向
return res # 返回反转链表的头节点
return recur(head, None) # 调用递归并返回
PyCharm调试代码
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
# Method 1 迭代/双指针
# cur, pre = head, None
# while cur:
# tmp = cur.next # 暂存后继节点 cur.next
# cur.next = pre # 修改 next 引用指向
# pre = cur # pre 暂存 cur
# cur = tmp # cur 访问下一节点
# return pre
# Method 2:递归
def recur(cur, pre):
if not cur: return pre # 终止条件
res = recur(cur.next, cur) # 递归后继节点
cur.next = pre # 修改节点引用指向
return res # 返回反转链表的头节点
return recur(head, None) # 调用递归并返回
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
listNode = ListNode(1)
tmp = listNode
for i in range(2, 6):
tmp.next = ListNode(i)
tmp = tmp.next
solution = Solution()
listNode = solution.reverseList(listNode)
print([listNode.val, listNode.next.val, listNode.next.next.val, listNode.next.next.next.val,
listNode.next.next.next.next.val])