Java - one loop and simple solution


  • 0
    J
    public class Solution {
    public RandomListNode copyRandomList(RandomListNode head) {
    	Map<Integer, RandomListNode> map = new HashMap<>();
        RandomListNode node = head, prev = null, cloneHead = null;
        while (node != null) {
        	RandomListNode clone;
        	if (map.containsKey(node.label)) {
        		clone = map.get(node.label);
        	} else {
        		clone = new RandomListNode(node.label);
        		map.put(clone.label, clone);
        	}
        	RandomListNode rand;
        	if (node.random != null) {
        		if (map.containsKey(node.random.label)) {
        			rand = map.get(node.random.label);
        		} else {
        			rand = new RandomListNode(node.random.label);
               		map.put(rand.label, rand);
        		}
        		clone.random = rand;
        	}
        	if (prev != null) {
        		prev.next = clone;
        	} else {
        		cloneHead = clone;
        	}
        	prev = clone;
        	node = node.next;
        }
        return cloneHead;
    }
    

    }


Log in to reply
 

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