题目描述
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)
题解
同样是先用一个虚拟头结点来处理头结点,便于操作,解决本题需要三个步骤,如下图
代码如下:
/**
* 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->next->next;
}
return dummyhead->next;
}
};
本题的注意事项:
1.关于虚拟头结点的使用:需要用到节点前一个结点的题目,由于头节点没有前驱节点,所以设置一个虚拟前驱,让头节点和后续中间节点处理方式一致即可。(划重点.jpg)
2.注意本题的三个步骤,最好画图,否则很容易思路混乱