classSolution:defreverseList(self,head: Optional[ListNode]) -> Optional[ListNode]:if head isNoneor head.next isNone:return head pre =None cur = headwhile cur isnotNone: tmp = cur.next cur.next = pre pre = cur cur = tmpreturn pre
时间复杂度:O(n)
空间复杂度:O(1)
递归
# 从树的角度来看递归classSolution:defreverseList(self,head: Optional[ListNode]) -> Optional[ListNode]:return self.recursive(head, None)defrecursive(self,cur,pre):if cur isNone:return pre tmp = cur.next cur.next = prereturn self.recursive(tmp, cur)# 注意此时的return
classDListNode:def__init__(self,val): self.val = val self.prev = self.next =Nonedefreverse(self,head): cur =Nonewhile head: cur = head head = cur.next cur.next = cur.prev cur.prev = curreturn cur