给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
输入:head = [1,2,3,4]
输出:[2,1,4,3]
示例 2:
输入:head = []
输出:[]
/**
* 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);
dummy->next = head;
ListNode *cur = dummy;
while(cur->next && cur->next->next)
{
ListNode *temp1 = cur->next;//记录临时节点
ListNode *temp2 = cur->next->next->next;
//交换
cur->next = cur->next->next;//步骤1
cur->next->next = temp1;//步骤2
cur->next->next->next = temp2;//步骤3
//准备下一个交换
cur = cur->next->next;
}
return dummy->next;
}
};
1.画图就会明白许多