javascript - 我在双向链表中的“removeElement(element)”中有问题
问题描述
我在列表中的删除元素中遇到问题。当我想删除列表中的元素时,它无法删除,但其他功能正常工作,例如在索引处添加和删除。
class Node{
constructor(element){
this.element = element;
this.right = null;
this.left = null;
}
}
class DLinkList{
constructor(){
this.head = null;
this.tail = null;
this.size = 0;
}
addFront(element){
var node = new Node(element);
var curr;
if(this.head === null){
this.head = node;
this.tail = node;
}else{
this.head.left = node;
node.right = this.head;
this.head = node;
}
this.size++;
}
addAtIndex(element,index){
var node = new Node(element);
var curr,prev;
if(this.head === null){
this.head = node;
this.tail = node;
}else{
var it = 0;
curr = this.head;
while(it < index){
it++;
prev = curr;
curr = curr.right;
}
node.right = curr;
prev.right = node;
node.left = prev;
}
this.size++;
}
removeAtIdex(index){
var curr,prev, it = 0;
if(index > 0 && index > this.size){
return false;
}else{
curr = this.head;
while(it < index){
it++;
prev = curr;
curr = curr.right;
}
prev.right = curr.right;
curr.right.left = prev;
}
this.size--;
}
removeElement(element){
var curr,prev = null;
curr = this.head;
while(curr != null){
if(curr.element === element){
if(prev === null){
this.head = curr.right;
}else{
prev.right = curr.right;
}
this.size--;
}
prev = curr;
curr = curr.next;
}
return -1;
}
printList(){
var curr = this.head;
var str = ''
while(curr){
str += curr.element + ' ';
curr = curr.right;
}
console.log(str);
}
}
var ll = new DLinkList();
ll.addFront(2);
ll.addFront(3);
ll.addFront(4);
ll.addAtIndex(5,2);
ll.printList();
ll.removeAtIdex(1);
ll.printList();
ll.removeElement(5);
ll.printList();
console.log(ll);
输出:
4 3 5 2
4 5 2
4 5 2
DLinkList {
head: Node {
element: 4,
right: Node { element: 5, right: [Node], left: [Circular] },
left: null
},
tail: Node {
element: 2,
right: null,
left: Node { element: 3, right: [Node], left: [Node] }
},
size: 3
}
解决方案
您使用不存在的属性名称:next
. 没有curr.next
。应该是curr.right
。
另外,不要忘记更新 left
和tail
:
if (curr.right === null) {
this.tail = prev;
} else {
curr.right.left = prev;
}
推荐阅读
- python - 带有字典值或键的 Python fillna
- github - Markdown 不显示我的 mp4 本地视频
- notifications - 在 Laravel 6 中使用队列发送 ResetPassword 通知 - 错误属性“视图”
- laravel-7 - 从 laravel 中的中间表获取数据
- pyspark - Sum() 和 count() 在 pyspark2 中不能与 agg 一起使用
- airflow - 气流:重新运行 DAG 无法加载以前运行的 XCOM
- memory-leaks - Dart Stream.periodic 内存泄漏
- python - 如何在使用 keras 的神经网络中输入一个包含 n 个项目的数组并输出一个大小为 k 的数组?
- python - 从python中定义的类调用函数?
- c++ - Visual Studio - 代码在发布但不在调试(C++)