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 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 }

第三遍:

 1 public class Solution {
 2     public ListNode swapPairs(ListNode head) {
 3         ListNode header = new ListNode(-1);
 4         header.next = head;
 5         ListNode cur = header;
 6         while(cur.next != null && cur.next.next != null){
 7             ListNode first = cur.next.next, second = cur.next;
 8             second.next = first.next;
 9             cur.next = first;
10             first.next = second;
11             cur = second;
12         }
13         return header.next;
14     }
15 }

 

posted on 2014-08-07 09:21  Step-BY-Step  阅读(123)  评论(0编辑  收藏  举报

导航