Monday, February 25, 2013

[LeetCode] Swap Nodes in Pairs

Thought:
Usually, we keep a sentinel before the head in Linked List problems.
Make sure that do not forget some links when linking nodes, which will make the whole list be divided into several parts.

Code:
public class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head == null) return head;
       
        ListNode sentinel = new ListNode(0);
        sentinel.next = head;
        ListNode ppre = sentinel;
        ListNode pre = head;
        ListNode current = head.next;
       
        while(current != null){
           
            pre.next = current.next;
            current.next = pre;
            ppre.next = current;           
            ppre = current;           
            current = pre.next;
           
            if(current != null){
                current = current.next;
                pre = pre.next;
                ppre = ppre.next;
            }
        }
        return sentinel.next;
    }
}

No comments:

Post a Comment