Thursday, June 12, 2014

Swap Nodes in Pairs

This question is a very fundamental one about manipulation of linked lists.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head == null || head.next == null) return head;
        ListNode preHead = new ListNode(0);
        preHead.next = head;
        ListNode preNode = head;
        ListNode pstNode = head.next;
        //swap first two
        preHead.next = pstNode;
        preNode.next = pstNode.next;
        pstNode.next = preNode;
        while(preNode.next!=null && preNode.next.next != null){
            ListNode tmpPre = preNode;
            preNode = preNode.next;
            pstNode = preNode.next;
         
            //swap
            tmpPre.next = pstNode;
            preNode.next = pstNode.next;
            pstNode.next = preNode;
        }
        return preHead.next;
    }
}

No comments:

Post a Comment