swap nodes in pairs

来源:互联网 发布:能够翻译文档软件 编辑:程序博客网 时间:2024/06/10 21:38
/*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.*//** * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next; * }; */ /* 利用双指针来修改head指针的值 */struct ListNode* swapPairs(struct ListNode* head){struct ListNode *per,*re;struct ListNode** tmp=&head;while((per=*tmp) && (re=per->next)){per->next=re->next;re->next=per;*tmp=re;tmp=&(per->next);}    return head;}