classSolution: defreverseList(self, head: ListNode) -> ListNode: # 三指针实现局部翻转链表 if head == Noneor head.next == None: return head sentry = None cur = head.next pre = head pre.next = sentry while cur: temp = cur.next cur.next = pre pre = cur cur = temp return pre
时间复杂度O(n),空间复杂度O(1)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution: defreverseList(self, head: ListNode) -> ListNode: # 栈 from collections import deque if head == Noneor head.next == None: return head deq = deque() while head: deq.append(head) head = head.next sentry = None while deq: cur = deq.popleft() cur.next = sentry sentry = cur return cur
时间复杂度O(n),空间复杂度O(n)
1 2 3 4 5 6 7 8 9 10 11 12
classSolution: defreverseList(self, head: ListNode) -> ListNode: # 每次生成新结点 if head == Noneor head.next == None: return head sentry = None while head: temp = ListNode(head.val) temp.next = sentry sentry = temp head = head.next return temp
时间复杂度O(n),空间复杂度O(n)
1 2 3 4 5 6 7 8 9
classSolution: defreverseList(self, head: ListNode) -> ListNode: # 递归 if head == Noneor head.next == None: return head last = self.reverseList(head.next) head.next.next = head head.next = None return last