題目連結(https://leetcode.com/problems/swap-nodes-in-pairs/description/)
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.)
第 24 天挑第 24 題,正好再熟悉一下 Linked list
[0, 100]
.0 <= Node.val <= 100
節點值可能為 0/**
**Input:** head = [1,2,3,4]
**Output:** [2,1,4,3]
**Input:** head = [1,2,3]
**Output:** [2,1,3]
**Input:** head = []
**Output:** []
node = head->next
(第二個節點)head->next = swapPairs(node->next)
→ 交換剩下的鏈表node->next = head
→ 將第二個節點指向第一個節點node
作為新的頭節點/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(!head || !head->next) return head;
ListNode* node = head->next;
head->next = swapPairs(node->next);
node->next = head;
return node;
}
};
Input: head = [1,2,3,4]
第一次呼叫 swapPairs(head=1)
head
= 1, head->next
= 2 → 不是 nullptr
node
= head->next = 2
執行:head->next = swapPairs(node->next) 即為swapPairs(head=3)
→ 進入下一層遞迴,node->next=head = 3
第二次呼叫 swapPairs(head=3)
head
= 3, head->next
= 4 → 不是 nullptr
node
= head->next = 4
執行:head->next = swapPairs(node->next)
→ 進入下一層遞迴,head = nullptr(node->next = nullptr)
第三次呼叫 swapPairs(head=nullptr)
head
= nullptr → 達到終止條件回到第二層(head=3, node=4)
head->next = swapPairs(node->next)
→ head->next = nullptr
node->next = head
→ 4->next = 3node
→ 回傳 4(作為新頭節點)回到第一層(head=1, node=2)
head->next = swapPairs(node->next)
→ head->next = 4
現在 1->next = 4
node->next = head
→ 2->next = 1
回傳 node
→ 回傳 2(作為新頭節點)
最終鏈表:2 → 1 → 4 → 3 → nullptr
原節點 | 交換後指向 |
---|---|
1 | 1->next = 4 |
2 | 2->next = 1 |
3 | 3->next = nullptr |
4 | 4->next = 3 |
指針操作:
head->next = swapPairs(node->next);
→ 將第一個節點連接到後續交換後的鏈表
node->next = head;
→ 將第二個節點指向第一個節點
遞迴 vs 迭代:
ps. 部分內容經 AI 協助整理