###### tags: `Leetcode` `medium` `list` `python` `Top 100 Liked Questions` # 24. Swap Nodes in Pairs ## [題目連結:] https://leetcode.com/problems/swap-nodes-in-pairs/ ## 題目: Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)  #### [圖片來源:] https://leetcode.com/problems/swap-nodes-in-pairs/ **Example 2:** ``` Input: head = [] Output: [] ``` **Example 3:** ``` Input: head = [1] Output: [1] ``` ## 解題想法: * 題目要求每兩個node自行交換 * 以example1為例 * 設nextCheck為紀錄下組起始位置 * 目前的兩個node自己處理好交換 * **Step1**: fast.next.next=fast (2指向3改成 2指向1) * **Step2**: slow.next=fast.next (slow指向2) * **Step3**: fast.next=nextCheck (最後讓1指向3) * step2、step3順序不能錯 * 移致下一組 * 示意圖:  ``` #原本: dum、slow head、fast nextCheck # 0 -> 1 -> 2 -> 3 -> 4 #第一組跑完 # # dum、slow head、fast nextCheck # 0 -> 2 -> 1 -> 3 -> 4 #所以處理下一組為 slow = fast 、fast=nextCheck ``` ## Python: ``` python= class ListNode(object): def __init__(self, val=0, next=None): self.val = val self.next = next def insert(self,node): if self.next == None: self.next=ListNode(node) else: self.next.insert(node) def printList(self): head = self tmp = [] while head: tmp.append(head.val) head = head.next print(tmp) class Solution(object): def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ dummy = ListNode(0) dummy.next = head fast = head slow = dummy nextCheck = None while fast and fast.next: #先設值給下個起始點 nextCheck = fast.next.next #斷開自己處理(2指向3改成 2指向1) fast.next.next = fast slow.next = fast.next fast.next = nextCheck #處理下一組 slow = fast fast = nextCheck return dummy.next if __name__ == '__main__': head = ListNode(1) head.insert(2) head.insert(3) head.insert(4) #head.printList() result = Solution() ans = result.swapPairs(head) ans.printList() ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up