题目
链接:24. 两两交换链表中的节点 - 力扣(LeetCode)
思路
画图模拟即可,分为三步,如图。
一轮结束后cur向后移动两位。
代码:
/**
* 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* dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode* cur = dummyHead;
while(cur->next != nullptr && cur->next->next != nullptr){
//记录临时结点
ListNode* temp = cur->next;
ListNode* temp1 = cur->next->next->next;
//三步
cur->next = cur->next->next;
cur->next->next = temp;
cur->next->next->next = temp1;
//cur移动两位,准备下一轮交换
cur = cur->next->next;
}
return dummyHead->next;
}
};