Javascript solution


  • 0
    X
    /**
     * Definition for singly-linked list with a random pointer.
     * function RandomListNode(label) {
     *     this.label = label;
     *     this.next = this.random = null;
     * }
     */
    
    /**
     * @param {RandomListNode} head
     * @return {RandomListNode}
     */
    var copyRandomList = function(head) {
        var cur = head;
        var copied = new RandomListNode(0);
        var copiedCur = copied;
        
        var map = new Map();
        while(cur !== null) {
            var temp = new RandomListNode(cur.label);
            copiedCur.next = temp;
            copiedCur = temp;
            
            map.set(cur, copiedCur);
            
            cur = cur.next;
        }
        
        cur = head;
        
        while(cur !== null) {
            var random = cur.random;
            if(random !== null) {
                map.get(cur).random = map.get(random);
            }
            cur = cur.next;
        }
        return copied.next;
    };
    

Log in to reply
 

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