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.

 

 1 public class Solution {
 2     public ListNode swapPairs(ListNode head) {
 3         // Note: The Solution object is instantiated only once and is reused by each test case.
 4         if(head == null || head.next == null) return head;
 5         ListNode newhead = head.next;
 6         ListNode first = head;
 7         ListNode second = head;
 8         ListNode pos = head;
 9         while(pos != null && pos.next != null){
10             first = pos;
11             second = pos.next;
12             pos = second.next;
13             if(pos == null || pos.next == null)
14                 first.next = pos;
15             else
16                 first.next = pos.next;
17             second.next = first;
18         }
19         return newhead;
20     }
21 }

 

 

 1  public class Solution {
 2     public ListNode swapPairs(ListNode head) {
 3         // Start typing your Java solution below
 4         // DO NOT write main() function
 5         ListNode helper = new ListNode(0);
 6         helper.next = head;
 7         ListNode n1 = helper, n2=head;
 8         
 9         while(n2!=null && n2.next!=null){
10             ListNode temp = n2.next.next;
11             n2.next.next=n1.next;
12             n1.next=n2.next;
13             n2.next=temp;
14             n1=n2;
15             n2=n1.next;
16         }
17         
18         return helper.next;
19     }
20 }

 第二遍:

 1 public class Solution {
 2     public ListNode swapPairs(ListNode head) {
 3         // Note: The Solution object is instantiated only once and is reused by each test case.
 4         if(head == null || head.next == null) return head;
 5         ListNode header = new ListNode(-1), first = head, second = head.next, cur = header;
 6         header. next = head;
 7         while(second != null ){
 8             first.next = second.next;
 9             second.next = first;
10             cur.next = second;
11             cur = first;
12             first = cur.next;
13             if(first != null)
14                 second = first.next;
15             else
16                 second = null;
17         }
18         return header.next;
19     }
20 }

 

posted on 2013-10-16 01:31  Step-BY-Step  阅读(180)  评论(0编辑  收藏  举报

导航