Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given1->2->3->4
, you should return the list as2->1->4->3
.
Your algorithm should use only constant space. You maynotmodify the values in the list, only nodes itself can be changed.
ListNode *swapPairs(ListNode *head)
{
if(head==NULL) return head;
int flag = 0;
ListNode *p = head;
ListNode *q = p->next;
while(q!=NULL)
{
p->next = q->next;
q->next = p;
if(flag==0)//第一次操作时保存头指针
{
head = q;
}
flag = 1;
ListNode *pre = p;//记录P
//p后移,q指向p的后继,如果p==NULL,p=p->next;报错,此时只需要直接
//将q赋NULL
p = p->next;
if(p!=NULL)
q = p->next;
else
q = NULL;
//若前面的p=p->next使得q==NULL,就不对了
if(q!=NULL)
pre->next = q;
}
return head;
}
关于链表的操作比较麻烦,虽然不会涉及到动态规划、搜索等复杂的算法思想,但是指针操作特别容易出错,面试或者笔试时,不容易准确快速的写出没有bug的代码,唯有平时好好总结,没事多看几遍啦。。。