题目:Swap Nodes in Pairs
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.
给定四个指针p1,p2,p3,p4,p1指向要转换的两个数据的前一个数据,p2,p3指向要转换的数据,p4指向需要转换的两个数据之后的那个数据。
p1 | p2 | p3 | p4 | ||
... | 2 | 3 | 4 | 5 | ... |
p3的下一个指向p2,p2的下一个指向p4,p1的下一个指向p3。
直到p3位空,或者p4位空,就退出程序。
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* swapPairs(struct ListNode* head) {
struct ListNode* p1=head;
struct ListNode* p2=head;
struct ListNode* p3=NULL;
struct ListNode* p4=NULL;
if(head==NULL)
{
return NULL;
}
else
{
while(true)
{
p3=p2->next;
if(p3==NULL)
{
printf("p3 is NULL\n");
return head;
}
else
{
p4=p3->next;
if(p1==head)
{
printf("At the beginning\n");
p3->next=p2;
p2->next=p4;
head=p3;
p1=p2; //重要
}
else
{
p3->next=p2;
p2->next=p4;
p1->next=p3;
p1=p2;
}
printf("p1 is %d\n",p1->val);
printf("p2 is %d\n",p2->val);
printf("p3 is %d\n\n",p3->val);
if(p4==NULL)
{
struct ListNode* t=head;
while(!t)
{
printf("Node is %d\n",t->val);
t=t->next;
}
printf("p4 is NULL");
return head;
}
else
{
p2=p4;
}
}
}
}
}