自己写的时候,想到了交换的方法,但是没有想到前面的点没有前继,导致[1 2 3 4 5]只出现结果[1 3 5]。当时是这样写的:
while()
{
p=head->next;
head->next=p->next;
p->next=head;
head=p->next->next;
}
由于p前面没有数据,导致消失。应该加一个前继,不然链表断了。
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode dummy(0),*pre=&dummy,*left(nullptr),*right(nullptr);
dummy.next=head;
while(pre!=NULL&&pre->next!=NULL&&pre->next->next!=NULL)
{
left=pre->next;
right=left->next;
left->next=right->next;
pre->next=right;
right->next=left;
pre=pre->next->next;
}
return dummy.next;
}
};