[LeetCode] Swap Nodes in Pairs 成對交換節點
阿新 • • 發佈:2018-12-27
Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given1->2->3->4
, you should return the list as2->1->4->3
.
Note:
- Your algorithm should use only constant extra space.
- You may not modify the values in the list's nodes, only nodes itself may be changed.
這道題不算難,是基本的連結串列操作題,我們可以分別用遞迴和迭代來實現。對於迭代實現,還是需要建立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; } };
類似題目:
參考資料: