Given the head of a singly linked list, reverse the list, and return the reversed list.
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
思路一:双指针
class Solution:def reverseList(self, head: ListNode) -> ListNode:cur, pre = head, Nonewhile cur:tmp = cur.next # 暂存后继节点 cur.nextcur.next = pre # 修改 next 引用指向pre = cur # pre 暂存 curcur = tmp # cur 访问下一节点return pre
class Solution:def reverseList(self, head: ListNode) -> ListNode:cur, pre = head, Nonewhile cur:cur.next, pre, cur = pre, cur, cur.nextreturn pre
方法二:递归
考虑使用递归法遍历链表,当越过尾节点后终止递归,在回溯时修改各节点的 next 引用指向。
recur(cur, pre) 递归函数:
终止条件:当 cur 为空,则返回尾节点 pre (即反转链表的头节点);
递归后继节点,记录返回值(即反转链表的头节点)为 res ;
修改当前节点 cur 引用指向前驱节点 pre ;
返回反转链表的头节点 res ;
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) # 调用递归并返回