Copy List with Random Pointer
A linked list is given such this each node contains an additional random pointer which could point to all node in the list or null.
Return a deep copy of the list.
https://leetcode.com/problems/copy-list-with-random-pointer/ The first direct violent two-wheeled traversal. The first round of the copy linked list, using a hash table to record each node, the second random traversal to the value of the list of random objects. And then slightly improved, a traversal can be found in the random are assigned, if not new out, to remember the missed array, and finally the missed node of the random again assigned value. Old version:
1 varCopyrandomlist =function(head) {2 varDict = {};3 varOriginnode =head;4 varNewNode =NewRandomlistnode (0);5 varOriginhead =head;6 varNewhead =NewNode;7 while(Originnode!==NULL){8 vartemp =NewRandomlistnode (Originnode.label);9Dict[originnode.label] =temp;TenNewnode.next =temp; One ANewNode =Newnode.next; -Originnode =Originnode.next; - } the -Originnode =Originhead; -NewNode =Newhead.next; - while(Originnode!==NULL){ + if(Originnode.random!==NULL){ -Newnode.random =Dict[originnode.random.label]; + } ANewNode =Newnode.next; atOriginnode =Originnode.next; - } - returnNewhead.next; -};
New:
1 /**2 * Definition for singly-linked list with a random pointer.3 * Function randomlistnode (label) {4 * this.label = label;5 * This.next = This.random = null;6 * }7 */8 9 /**Ten * @param {randomlistnode} head One * @return {randomlistnode} A */ - varCopyrandomlist =function(head) { - varDict = {}; the varMissed = []; - varOriginnode =head; - varNewNode =NewRandomlistnode (0); - varOriginhead =head; + varNewhead =NewNode; - while(Originnode!==NULL){ + vartemp =NewRandomlistnode (Originnode.label); ADict[originnode.label] =temp; atNewnode.next =temp; -NewNode =Newnode.next; - - if(Originnode.random!==NULL){ - if(Dict[originnode.random.label]) { -Newnode.random =Dict[originnode.random.label]; in}Else{ -Newnode.random =OriginNode.random.label; to Missed.push (Newnode.label); + } - } theOriginnode =Originnode.next; * } $ for(vari = 0; i < missed.length; i++){Panax Notoginseng varCurr =Dict[missed[i]]; -Curr.random =Dict[curr.random]; the } + returnNewhead.next; A};
[Leetcode] [JavaScript] Copy List with Random Pointer