Copy List with Random Pointer

lc 138 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) {
        if (head == null) return head;
        RandomListNode res = head;
        Map<RandomListNode, RandomListNode> map = new HashMap<>();
        while (head != null) {
            RandomListNode cur = map.getOrDefault(head, new RandomListNode(head.label));
            if (head.next != null) {
                RandomListNode next = map.getOrDefault(head.next, new RandomListNode(head.next.label));
                cur.next = next;
                map.put(head.next, next);
            }
            if (head.random != null) {
                RandomListNode random = map.getOrDefault(head.random, new RandomListNode(head.random.label));
                cur.random = random;
                map.put(head.random, random);
            }
            map.put(head, cur);
            head = head.next;
        }

        return map.get(res);
    }
}

results matching ""

    No results matching ""