Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
奇数位和偶数位互换,若是奇数个,不用管最后一个
解法一:(C++)
1 ListNode* swapPairs(ListNode* head) { 2 if(!head) 3 return NULL; 4 ListNode* dummy=new ListNode(-1),*cur=dummy; 5 dummy->next=head; 6 while(cur->next&&cur->next->next){ 7 ListNode* t=cur->next->next; 8 cur->next->next=t->next; 9 t->next=cur->next; 10 cur->next=t; 11 cur=t->next; 12 } 13 return dummy->next; 14 }
java:
1 public ListNode swapPairs(ListNode head) { 2 if(head==null) 3 return null; 4 ListNode dummy=new ListNode(-1),pre=dummy; 5 dummy.next=head; 6 while(pre.next!=null&&pre.next.next!=null){ 7 ListNode t=pre.next.next; 8 pre.next.next=t.next; 9 t.next=pre.next; 10 pre.next=t; 11 pre=t.next; 12 } 13 return dummy.next; 14 }
方法二:使用递归的方法,递归遍历到末尾两个,然后交换末尾两个,依次往前遍历(C++)
1 ListNode* swapPairs(ListNode* head) { 2 if(!head||!head->next) 3 return head; 4 ListNode* t=head->next; 5 head->next=swapPairs(head->next->next); 6 t->next=head; 7 return t; 8 }