搜索此博客

2012年10月25日星期四

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.
01 public ListNode swapPairs(ListNode head) {
02     if(head==null || head.next==null)
03         return head;
04     ListNode first=head;
05     ListNode second=head.next;              
06     first.next=second.next;
07     second.next=first;
08     head=second;
09     ListNode prev=first;
10     first=first.next;
11   
12     while(first!=null && first.next!=null)
13     {
14         second=first.next;
15         first.next=second.next;
16         second.next=first;
17         prev.next=second;
18                   
19         prev=first;
20         first=first.next;
21     }
22     return head;
23 }

没有评论:

发表评论