C# accepted solution


  • 0
    M
    public RandomListNode CopyRandomList(RandomListNode head) {
        if(head == null)
            return null;
            
        var map = new Dictionary<RandomListNode, RandomListNode>();
        var node = head;
        int count = 0;
        while(node != null && !map.ContainsKey(node)) // cycle check
        {
            count++;
            var newNode = new RandomListNode(node.label);
            map.Add(node, newNode);
            node = node.next;
        }
        
        node = head;
        for(int i = 0; i < count; i++) // prevents cycle
        {
            var newNode = map[node];
            if(node.next != null)
                newNode.next = map[node.next];
                
            if(node.random != null)
                newNode.random = map[node.random];
                
            node = node.next;
        }
        
        return map[head];
    }

Log in to reply
 

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