""" ✅ 較容易理解 使用雙指標當前與前一個node位置 """ classSolution: defswapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]: dummy = ListNode(None, head) prev, cur = dummy, head while cur and cur.next: prev.next = cur.next# dummy -> 20 cur.next = cur.next.next# 10 -> 30 prev.next.next = cur # 20 -> 10
# 移動prev, cur prev = cur cur = cur.next return dummy.next
時間複雜度: O(n) 空間複雜度: O(1)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
""" 遞迴 """ classSolution: defswapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]: if head isNoneor head.nextisNone: return head
# 待翻转的两个node分别是pre和cur pre = head cur = head.next next = head.next.next cur.next = pre # 交换 pre.next = self.swapPairs(next) # 将以next为head的后续链表两两交换 return cur