Javascript 基于值从链表中删除节点
我正在处理一个Hackerrank问题,并试图删除所有大于某个特定值的节点 这是它们的基本实现Javascript 基于值从链表中删除节点,javascript,data-structures,linked-list,nodes,Javascript,Data Structures,Linked List,Nodes,我正在处理一个Hackerrank问题,并试图删除所有大于某个特定值的节点 这是它们的基本实现 const SinglyLinkedListNode = class{ constructor(value) { this.value = value; this.next = null; } }; const SinglyLinkedList = class { constructor() { this.head = null; this.tail =
const SinglyLinkedListNode = class{
constructor(value) {
this.value = value;
this.next = null;
}
};
const SinglyLinkedList = class {
constructor() {
this.head = null;
this.tail = null;
}
insertNode(value) {
const node = new SinglyLinkedListNode(value);
if(!this.head) {
this.head = node;
} else {
this.tail.next = node;
}
this.tail = node;
}
};
我删除节点的功能如下
SinglyLinkedList.prototype.removeNodes = function(listHead, x){
let currentNode = listHead;
while(currentNode !== null && currentNode.next !== null) {
let next = currentNode.next;
while (next !== null && next.value > x) {
next = next.next
}
currentNode.next = next
if(currentNode.next === null) {
break;
}
}
return currentNode
}
参数是:listhead-对根节点的引用,以及x-用于过滤链接列表的整数值
例如,LL是1->2->4->3->5,我需要删除所有大于x(3)的节点,并保持LL顺序的完整性。
结果应该是1->2->3
我不明白为什么我总是得到这个.tail.value=5而不是
this.tail.value=3,this.tail.next=null
这是一个原因,
尾部
必须被明确重写,因为它保留了对未链接节点的引用。在运行函数之前,列表如下所示:
list: head tail
1 -> 2 -> 3 -> 4 -> 5
之后,尾巴仍然指向5,尽管它没有链接:
list: head tail
1 -> 2 -> 3 5
要解决此问题,只需重写函数末尾的尾部:
return this.tail = currentNode;
此外,您还必须实际遍历列表,因此添加一个
currentNode = currentNode.next;
在外部
的末尾,while
导致尾部
必须被明确重写,否则它会保留对未链接节点的引用。在运行函数之前,列表如下所示:
list: head tail
1 -> 2 -> 3 -> 4 -> 5
之后,尾巴仍然指向5,尽管它没有链接:
list: head tail
1 -> 2 -> 3 5
要解决此问题,只需重写函数末尾的尾部:
return this.tail = currentNode;
此外,您还必须实际遍历列表,因此添加一个
currentNode = currentNode.next;
在外部
的末尾,while
Ok,但是似乎如果console.log(this.tail.next),我仍然没有看到null。参考文献仍然指向4@kevin哦,你把列表遍历搞砸了,请看Ok,但是如果console.log(this.tail.next),我仍然看不到null。参考文献仍然指向4@kevin哦,你把列表遍历搞砸了,明白吗