24.Swap Nodes in Pairs

1-

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head == null || head.next == null)
            return head;
        ListNode newHead = head.next;
        ListNode tmp = head;
        //Reverse Head Part
        tmp.next = newHead.next;
        newHead.next = tmp;
        ListNode left = tmp;
        ListNode right = tmp.next;
        //Reverse Middle Part
        while(right != null && right.next != null){
            left.next = right.next;
            right.next = right.next.next;
            left.next.next = right;
            left = left.next.next;
            right = right.next;
        }
        return newHead;
    }
}

2-Improve Dummy Head

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head == null || head.next == null)
            return head;
        ListNode preHead = new ListNode(0);
        preHead.next = head;
        ListNode left = preHead;
        ListNode right = preHead.next;
        //Reverse Middle Part
        while(right != null && right.next != null){
            left.next = right.next;
            right.next = right.next.next;
            left.next.next = right;
            left = left.next.next;
            right = right.next;
        }
        return preHead.next;
    }
}

3Recursive - Really Smart Way

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head == null || head.next == null)
            return head;
        ListNode newHead = head.next;
        head.next = swapPairs(head.next.next);
        newHead.next = head;
        return newHead;
    }
}

results matching ""

    No results matching ""