Copy List with Random Pointer
A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
Return a deep copy of the list.
https://leetcode.com/problems/copy-list-with-random-pointer/
第一把直接暴力两轮遍历。第一轮遍历copy链表,用hash表记录下各个节点,第二乱遍历去赋值链表里的random对象。
然后稍稍改进了一下,一次遍历里把能的找到的random都赋上,如果还没new出来,记到missed数组中,最后把missed的节点中的random再赋上值。
旧版:
1 var copyRandomList = function(head) { 2 var dict = {}; 3 var originNode = head; 4 var newNode = new RandomListNode(0); 5 var originHead = head; 6 var newHead = newNode; 7 while(originNode !== null){ 8 var temp = new RandomListNode(originNode.label); 9 dict[originNode.label] = temp; 10 newNode.next = temp; 11 12 newNode = newNode.next; 13 originNode = originNode.next; 14 } 15 16 originNode = originHead; 17 newNode = newHead.next; 18 while(originNode !== null){ 19 if(originNode.random !== null){ 20 newNode.random = dict[originNode.random.label]; 21 } 22 newNode = newNode.next; 23 originNode = originNode.next; 24 } 25 return newHead.next; 26 };
新版:
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 /** 10 * @param {RandomListNode} head 11 * @return {RandomListNode} 12 */ 13 var copyRandomList = function(head) { 14 var dict = {}; 15 var missed = []; 16 var originNode = head; 17 var newNode = new RandomListNode(0); 18 var originHead = head; 19 var newHead = newNode; 20 while(originNode !== null){ 21 var temp = new RandomListNode(originNode.label); 22 dict[originNode.label] = temp; 23 newNode.next = temp; 24 newNode = newNode.next; 25 26 if(originNode.random !== null){ 27 if(dict[originNode.random.label]){ 28 newNode.random = dict[originNode.random.label]; 29 }else{ 30 newNode.random = originNode.random.label; 31 missed.push(newNode.label); 32 } 33 } 34 originNode = originNode.next; 35 } 36 for(var i = 0; i < missed.length; i++){ 37 var curr = dict[missed[i]]; 38 curr.random = dict[curr.random]; 39 } 40 return newHead.next; 41 };
时间: 2024-10-05 05:07:10