138. Copy List with Random Pointer

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

/**
 * Definition for singly-linked list with a random pointer.
 * class RandomListNode {
 *     int label;
 *     RandomListNode next, random;
 *     RandomListNode(int x) { this.label = x; }
 * };
 */
public class Solution {
    public RandomListNode copyRandomList(RandomListNode head) {
        RandomListNode p = head;
        while(p != null){
            RandomListNode next = p.next;
            RandomListNode dup = new RandomListNode(p.label);
            dup.next = next;
            p.next =dup;
            p =next;
        }


        p = head;
        while(p != null){
            if(p.random != null){
                p.next.random = p.random.next;
            }
            p = p.next.next;
        }

        RandomListNode dummy = new RandomListNode(-1);
        RandomListNode dupTail = dummy;
        p = head;
        while(p != null){
            RandomListNode next = p.next.next;
            dupTail.next = p.next;
            p.next = next;
            dupTail = dupTail.next;
            p = next;
        }

        return dummy.next;

    }
}

results matching ""

    No results matching ""