[LeetCode] 24. Swap Nodes in Pairs 成對交換節點


 

Given a linked list, swap every two adjacent nodes and return its head.

You may not modify the values in the list's nodes, only nodes itself may be changed.

 

Example:

Given 1->2->3->4, you should return the list as 2->1->4->3.

 

這道題不算難,是基本的鏈表操作題,我們可以分別用遞歸和迭代來實現。對於迭代實現,還是需要建立 dummy 節點,注意在連接節點的時候,最好畫個圖,以免把自己搞暈了,參見代碼如下:

 

解法一:

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        ListNode *dummy = new ListNode(-1), *pre = dummy;
        dummy->next = head;
        while (pre->next && pre->next->next) {
            ListNode *t = pre->next->next;
            pre->next->next = t->next;
            t->next = pre->next;
            pre->next = t;
            pre = t->next;
        }
        return dummy->next;
    }
};

 

遞歸的寫法就更簡潔了,實際上利用了回溯的思想,遞歸遍歷到鏈表末尾,然后先交換末尾兩個,然后依次往前交換:

 

解法二:

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if (!head || !head->next) return head;
        ListNode *t = head->next;
        head->next = swapPairs(head->next->next);
        t->next = head;
        return t;
    }
};

 

Github 同步地址:

https://github.com/grandyang/leetcode/issues/24

 

類似題目:

Reverse Nodes in k-Group

 

參考資料:

https://leetcode.com/problems/swap-nodes-in-pairs

https://leetcode.com/problems/swap-nodes-in-pairs/discuss/11030/My-accepted-java-code.-used-recursion.

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM