class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(!head||!head->next)
return head;
ListNode *headptr=new ListNode(0);
headptr->next=head;
ListNode* pre;
ListNode *before;
ListNode *after;
ListNode *nextpair;
pre=headptr;
before=head;
after=head->next;
while(after!=NULL&&before!=NULL)
{
nextpair=after->next;
after->next=before;
pre->next=after;
pre=before;
if(nextpair!=NULL)
{
before=nextpair;
after=nextpair->next;
if(!after)
{
pre->next=before;
}
}
else {
before->next=NULL;
break;
}
}
return headptr->next;
}
};
24. Swap Nodes in Pairs
最新推荐文章于 2021-12-31 22:38:21 发布