lintcode-easy-Swap Nodes in Pairs

Given a linked list, swap every two adjacent nodes and return its head.

Given 1->2->3->4, you should return the list as 2->1->4->3.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    /**
     * @param head a ListNode
     * @return a ListNode
     */
    public ListNode swapPairs(ListNode head) {
        // Write your code here
        if(head == null || head.next == null)
            return head;
        
        ListNode fakehead = new ListNode(0);
        fakehead.next = head;
        
        ListNode prev = fakehead;
        ListNode curr = head;
        ListNode next = head.next;
        
        while(next != null && next.next != null){
            curr.next = next.next;
            next.next = curr;
            prev.next = next;
            
            curr = curr.next;
            next = curr.next;
            prev = prev.next.next;
        }
        
        if(next != null){
            curr.next = next.next;
            next.next = curr;
            prev.next = next;
        }
        
        return fakehead.next;
    }
}

 

posted @ 2016-03-07 08:44  哥布林工程师  阅读(94)  评论(0编辑  收藏  举报