Simple Java Solution


  • 0
    M

    Deep copying a linked list is fairly simple. Just loop through and create a node based on the original list node. But in this problem, it became tricky due to the random nodes. The random nodes might point to a node which is already copied or it might point to a node which will be created later. To overcome this, I have used a map that contains all the nodes. Checked that map before creating any node. If node is already created due to random node, used the existing one.

    /**
     * Definition for singly-linked list with a random pointer.
     * class RandomListNode {
     *     int label;
     *     RandomListNode next, random;
     *     RandomListNode(int x) { this.label = x; }
     * };
     */
    import java.util.*;
    public class Solution {
       public RandomListNode copyRandomList(RandomListNode head) {
            if(head == null) {
                return null;
            }
    
            Map<RandomListNode, RandomListNode> nodes = new HashMap<>();
            RandomListNode newHead = null;
            RandomListNode curNode = head;
            RandomListNode prevNewNode = null;
    
            while(curNode != null) {
                RandomListNode newNode = nodes.get(curNode); //check if already exists.
                if(newNode == null) {
                    newNode = new RandomListNode(curNode.label);
                    nodes.put(curNode, newNode);
                }
    
                //set random
                if(curNode.random != null) {
                    RandomListNode randomNode = nodes.get(curNode.random); // check if the random node already created.
                    if(randomNode == null) {
                        randomNode = new RandomListNode(curNode.random.label);
                        nodes.put(curNode.random, randomNode);
                    }
                    newNode.random = randomNode;
                }
    
                //set next
                if(curNode == head) {
                    newHead = newNode;
                } else {
                    prevNewNode.next = newNode;
                }
                prevNewNode = newNode;
                curNode = curNode.next;
    
            }
            return newHead;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.