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.
思路:将链表拆分,然后再合并
List *swapPairs(List *head) { if(head == NULL || head->next == NULL) return head; List* ji=head; List* ou = head->next; List* temp1,*temp2; List* l1= head; List* l2 = head->next; temp1 = l2->next; while(temp1 != NULL) { temp2 = temp1->next; l1->next = temp1; l2->next = temp2; l1 = temp1; l2 = temp2; if(l2 !=NULL) temp1 = l2->next; else temp1 = NULL; } if(l1 != NULL) l1->next =NULL; if(l2 != NULL) l2->next = NULL; temp1 = ou; while(temp1 != NULL&&temp1->next != NULL) { temp2 = ji->next; ji->next = temp1->next; temp1->next = ji; temp1 = ji->next; ji = temp2; } temp1->next = ji; return ou; }
原文地址:http://blog.csdn.net/yusiguyuan/article/details/45022871