joshita / dev

Published

- 1 min read

Deep clone a linked list with random pointer in each node

img of Deep clone a linked list with random pointer in each node

Deep clone a linked list with random pointer

Construct a deep copy of the list. The deep copy should consist of exactly n brand new nodes, where each new node has its value set to the value of its corresponding original node. Both the next and random pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. None of the pointers in the new list should point to nodes in the original list.

       private RandomNode copyListWithRandomPointer(RandomNode head) {
        RandomNode oldNode = head;
        RandomNode newNode = createACloneNode(oldNode);
        visitedHash.put(oldNode, newNode);
        while (oldNode != null) {
                newNode.next = createACloneNode(oldNode.next);
                newNode.random = createACloneNode(oldNode.random);
                
                oldNode = oldNode.next;
                newNode = newNode.next;
        }
        return newHead;
    }

    private RandomNode createACloneNode(RandomNode node) {

        if(node == null){
            return null;
        }

        if(visitedHash.containsKey(node)) {
            return visitedHash.get(node);
        } else {
            visitedHash.put(node, new RandomNode(node.val, null, null));
            return visitedHash.get(node);
        }
    }