138.Copy List with Random Pointer

1- Copy with Two Pass

/**
 * 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) {
        //Key: original node; Val: copyed node
        Map<RandomListNode, RandomListNode> map = new HashMap<>();
        RandomListNode cur = head;
        //First Round, we only create new Node
        while(cur != null){
            map.put(cur, new RandomListNode(cur.label));
            cur = cur.next;
        }

        //Second Round, we link pointer of next and random.
        cur = head;
        while(cur != null){
            RandomListNode cloneCur = map.get(cur);
            RandomListNode cloneNext = map.get(cur.next);
            RandomListNode cloneRandom = map.get(cur.random);
            cloneCur.next = cloneNext;
            cloneCur.random = cloneRandom;
            cur = cur.next;
        }
        return map.get(head);
    }
}

results matching ""

    No results matching ""