我正在尝试合并两个链接列表,但是由于某种原因,它说它无法读取null值-当定义了我的值时。
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.length = 0;
}
add(value) {
var node = new Node(value);
var current;
if (this.head == null) {
this.head = node
} else {
current = this.head
while (current.next) {
current = current.next;
}
current.next = node
}
this.length++
}
}
function mergeLinkedList(l1, l2) {
let newList = new LinkedList()
let currentNode1 = l1.head
let currentNode2 = l2.head
while (currentNode1 || currentNode2) {
if (currentNode1.value <= currentNode2.value) {
newList.add(currentNode1)
newList.add(currentNode2)
} else {
newList.add(currentNode2)
newList.add(currentNode1)
}
currentNode1 = currentNode1.next
currentNode2.head = currentNode2.next
}
return newList
}
let l1 = new LinkedList()
l1.add(1)
l1.add(2)
l1.add(4)
let l2 = new LinkedList()
l2.add(1)
l2.add(3)
l2.add(4)
mergeLinkedList(l1, l2)
这应该返回一个1->1->2->3->4->4
的新链表,但是在命中以下if语句时返回一个错误:if (currentNode1.value <= currentNode2.value)
指出它无法读取null的属性“值”,但该值在这里明确定义。
答案 0 :(得分:1)
您可以独立检查节点并添加值而不是节点本身。
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.length = 0;
}
add(value) {
var node = new Node(value);
var current;
if (this.head == null) {
this.head = node
} else {
current = this.head
while (current.next) {
current = current.next;
}
current.next = node
}
this.length++
}
}
function mergeLinkedList(l1, l2) {
let newList = new LinkedList()
let currentNode1 = l1.head
let currentNode2 = l2.head
while (currentNode1 && currentNode2) {
if (currentNode1.value <= currentNode2.value) {
newList.add(currentNode1.value)
currentNode1 = currentNode1.next
} else {
newList.add(currentNode2.value)
currentNode2 = currentNode2.next
}
}
while (currentNode1) {
newList.add(currentNode1.value)
currentNode1 = currentNode1.next
}
while (currentNode2) {
newList.add(currentNode2.value)
currentNode2 = currentNode2.next
}
return newList
}
let l1 = new LinkedList()
l1.add(1)
l1.add(2)
l1.add(4)
console.log(l1);
let l2 = new LinkedList()
l2.add(1)
l2.add(3)
l2.add(4)
console.log(l2);
console.log(mergeLinkedList(l1, l2))
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:0)
您有
同时(currentNode1 || currentNode2)
使得只需要一个节点不为null即可进入while循环。但是之后你就拥有了
如果(currentNode1.value <= currentNode2.value)
正在访问两个节点的值。在这种情况下,您可能会在while循环中使用currentNode2 == null出现错误。
您应将while循环条件写为
while (currentNode1 && currentNode2){
.
.
.
}
然后还有另一个条件来检查您的链接列表,并附加其余尚未为空的列表。