Saturday, April 5, 2014

leetcode: Swap Nodes in Pairs

Code:

 public ListNode swapPairs(ListNode head) {
         if(head == null || head.next == null) return head;
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        
        ListNode last = dummy;
        while(last.next != null && last.next.next != null){
            ListNode prev = last.next;
            ListNode current = last.next.next;
            
            last.next = current;
            prev.next = current.next;
            current.next = prev;
            
            last = prev;
        }
        return dummy.next;
    }

No comments:

Post a Comment