# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next classSolution: defreverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: cur,pre = head,None while cur: tmp = cur.next cur.next = pre pre = cur cur = tmp
return pre
3、递归
考虑使用递归法遍历链表,当越过尾节点后终止递归,在回溯时修改各节点的
next 引用指向。
1 2 3 4 5 6 7 8 9 10
classSolution: defreverseList(self, head: ListNode) -> ListNode: defrecur(cur, pre): ifnot cur: return pre # 终止条件 res = recur(cur.next, cur) # 递归后继节点 cur.next = pre # 修改节点引用指向 return res # 返回反转链表的头节点