思路:创建虚拟头节点dummyhead,cur指针指向dummyhead,让cur指向cur后第二个节点,cur后的第二个节点指向cur后的第一个节点,cur后的第一个节点再指向cur后的第三个节点,完成第一次交换,再将cur向后移动两格完成下一次交换,用两个变量指针temp和temp1来保存值完成链接。最后停止while循环的条件,当节点是奇数时,cur->next就是最后一个节点,没有下一个节点可以与最后一个节点交换,停止交换即cur->next->next=NULL;当节点时偶数个时,完成最后一次交换时(最后一个节点和倒数第二个节点完成交换),为了交换的连续性,cur还要移动到最后一个节点,来判断下一次是否进行交换,此时cur->next=NULL,就是结束while的条件。
易错点:while里先写cur->next=NULL,再是cur->next->next=NULL,有空指针报错,因为反过来,那么如果cur->next=NULL,那它的next就会有空指针报错。链表中指向,我以为还是要->next(以为要cur->next->next->next=temp)结果不用。
题解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) {
ListNode *dummyhead=new ListNode();
dummyhead->next=head;
ListNode *cur=dummyhead;
while(cur->next!=NULL&&cur->next->next!=NULL)
{
ListNode *temp=cur->next;
ListNode *temp1=cur->next->next->next;
cur->next=cur->next->next;
cur->next->next=temp;//这一行
temp->next=temp1;
cur=cur->next->next;
}
return dummyhead->next;
}
};