给你单链表的头节点 head
,请你反转链表,并返回反转后的链表。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
#双指针法
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
cur = head
pre = None # 直接写None就行不用写ListNode(None)
while (cur != None):
temp = cur.next
cur.next = pre
pre = cur
cur = temp
# 上面两行注意先后顺序。若先cur = temp 后pre = cur,则 pre = cur = temp,就不对了
return pre
#迭代法
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
def reverse(cur, pre):
if cur != None:
temp = cur.next
cur.next = pre
# reverse(temp, cur) #❗这种写法错误
return reverse(temp, cur) #这种写法正确
else:
return pre
return reverse(head, None)
关于代码随想录上写的递归法二:
参考博客代码随想录算法训练营第3天 | 203.移除链表元素、707.设计链表、206.反转链表 – 虚空裂隙 (tftree.top)