class ListNode(object): def __init__(self, val=0, next=None): self.val = val self.next = next class Solution(object): def swapPairs(self, head): temp = ListNode(None, head) prev, cur = temp, head while cur and cur.next: prev.next = cur.next cur.next = cur.next.next prev.next.next = cur prev, cur = cur, cur.next return temp.next #for test node = ListNode(1, ListNode(2, ListNode(3, ListNode(4)))) sol = Solution().swapPairs(node) while sol: print(sol.val, end=" ") sol = sol.next |
LinkedList 真的是我很不拿手的部分
然後回傳temp.next指到新的ListNode
就是題目要的東西了
這個要多練...吧?