Saturday, March 11, 2017

24. Swap Nodes in Pairs

[2ND TRY]
Version #2 Iteration Version

 100.00 % 
class Solution {
    public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(0);
dummy.next = head;
//   prev  p1   p2  next
// dummy -> 1 -> 2 -> 3 -> 4
// dymmy -> p2 -> p1 -> next -> ...
ListNode prev = dummy;
ListNode p1;
ListNode p2;
ListNode next;
while (prev.next != null && prev.next.next != null) {
p1 = prev.next;
p2 = p1.next;
next = p2.next;
prev.next = p2;
p2.next = p1;
p1.next = next;
prev = p1;
}
return dummy.next;
}
}

[1ST TRY]
Version #1 Recursive version
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode temp = swapPairs(head.next.next);
        ListNode newHead = head.next;
        head.next.next = head;
        head.next = temp;
        return newHead;
     
    }
}

No comments:

Post a Comment