https://leetcode.cn/problems/swap-nodes-in-pairs/
所谓交换节点,就是要将A->B->C->D改为A->C->B->D
那么,可以如此分布进行。
1.A->B->C
D->C
2.A->B->C
D->B
3.A->D->B->C
这样就能不改变A,D节点而交换B,C节点
图解:
/*画的好丑啊*/
那么,话不多说,咱们上代码!
/** * 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 == nullptr || head -> next == nullptr) return head; ListNode* cur = new ListNode(0); cur -> next = head; if(cur -> next != nullptr && cur -> next -> next != nullptr) { ListNode* slow = cur -> next; ListNode* fast = slow -> next; slow -> next = fast -> next; fast -> next = slow; cur -> next = fast; head = fast; cur = slow; } while(cur -> next != nullptr && cur -> next -> next != nullptr) { ListNode* slow = cur -> next; ListNode* fast = slow -> next; slow -> next = fast -> next; fast -> next = slow; cur -> next = fast; cur = slow; } return head; } };
需要注意的是,由于头节点与其他节点更换后,头节点需要改变,所以需要单独交换。