24 Swap Nodes in Pairs
链接:https://leetcode.com/tag/linked-list/
问题描述:
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
Hide Tags Linked List
链表中每两个为单位交换顺序。
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(head==NULL||head->next==NULL) return head;
ListNode *t=new ListNode(0);
ListNode *p1=head,*p2=head->next,*next=head->next->next,*temp=t;
while(p1&&p2)
{
temp->next=p2;
temp=temp->next;
temp->next=p1;
temp=temp->next;
p1=p2=NULL;
if(next)
{
p1=next;
next=next->next;
}
if(next)
{
p2=next;
next=next->next;
}
}
if(p1)
{
temp->next=p1;
temp=temp->next;
}
temp->next=NULL;
temp=t->next;
delete t;
return temp;
}
};
代码简化版本:
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(head==NULL||head->next==NULL) return head;
ListNode *t=new ListNode(0);
ListNode *next,*temp=t;
while(head&&head->next)
{
next=head->next->next;
temp->next=head->next;
temp->next->next=head;
temp=head;
temp->next=NULL;
head=next;
}
if(head)
temp->next=head;
temp=t->next;
delete t;
return temp;
}
};