这是leetcode第138题。带随机指针的复制列表
下面是我的代码:给定一个长度为n的链表,使得每个节点包含一个额外的随机指针,它可以指向列表中的任何节点,或null。
构造列表的深拷贝。深拷贝应该包括正好有n个全新的节点,每个新节点的值设置为对应的原始节点的值。下一个和随机新节点的指针应该指向复制列表中的新节点这样的指针在原始列表和复制列表表示相同的列表状态。新列表中的指针都不指向到原列表中的节点.
function Node(val, next, random) {
this.val = val;
this.next = next;
this.random = random;
};
var copyRandomList = function (head) {
const old2NewMap = new Map()
let pointer = head;
while (pointer) {
const tempNewNode = new Node(pointer.val);
old2NewMap.set(pointer, tempNewNode)
pointer = pointer.next;
}
pointer = head;
while (pointer) {
const tempNewNode = old2NewMap.get(pointer);
tempNewNode.next = old2NewMap.get(pointer.next)
tempNewNode.random = old2NewMap.get(pointer.random)
pointer = pointer.next;
}
return old2NewMap.get(head)
};
它可以在我的本地PC上传递,至少没有错误。下面是测试代码:
const th1Node = new Node(7, null, null)
const th2Node = new Node(13, null, null)
const th3Node = new Node(11, null, null)
const th4Node = new Node(10, null, null)
const th5Node = new Node(1, null, null)
th1Node.next = th2Node;
th1Node.random = null;
th2Node.next = th3Node;
th2Node.random = th1Node;
th3Node.next = th4Node;
th3Node.random = th5Node;
th4Node.next = th5Node;
th4Node.random = th3Node;
th5Node.next = null;
th5Node.random = th1Node;
console.log(copyRandomList(th1Node))
但是,当我提交时告诉我错了:
Line 83 in solution.js
node = node.next;
^
TypeError: Cannot read properties of undefined (reading 'next')
Line 83: Char 25 in solution.js (Object.serializer.isCyclic)
Line 109: Char 24 in solution.js (Object.serializer.serializeLinkedList)
Line 165: Char 30 in solution.js (Object.<anonymous>)
Line 16: Char 8 in runner.js (Object.runner)
Line 28: Char 26 in solution.js (Object.<anonymous>)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
我不知道为什么
node.next
假定为列表中最后一个节点的null
。但是当你这样做的时候:
tempNewNode.next = old2NewMap.get(pointer.next)
pointer.next
为null
,old2NewMap
中没有该值的条目。get()
返回undefined
,而不是null
。您需要将其转换为null
。
tempNewNode.next = old2NewMap.get(pointer.next) || nulll