兩兩節點做交換
這邊的想法是說,我先用兩者指針分別記錄,要交換的節點 p1 跟 p2
想像 swapPairs 這個函數本身會返回 p2 的位置回來
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
// 終止條件
if(!head || !head->next) return head;
// 用指針分別記錄要交換的兩個節點
ListNode* l1 = head;
ListNode* l2 = head->next;
l1->next = swapPairs(l2->next);
l2->next = l1;
return l2;
}
};
這邊就要建立虛擬節點
/**
* 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) {
ListNode* dummy = new ListNode(0);
ListNode* curr = dummy;
dummy->next = head;
while(head && head->next){
ListNode* l1 = head;
ListNode* l2 = head->next;
// 交換節點
curr->next = l2;
l1->next = l2->next;
l2->next = l1;
// 移動指標
curr = curr->next->next; // 移動到目前交換對的尾端
head = l1->next; // 移動到下一對的起點
}
return dummy->next;
}
};