【发布时间】:2020-09-28 22:12:58
【问题描述】:
我需要在 LinkedList 原型中实现 addInPos 方法,但我不知道它在我的代码中有什么问题……因为测试没有通过。 在 LinkedList 原型中实现 addInPos 方法,该方法必须在指定位置添加一个元素。两个数据都将作为参数 (pos, value) 提供。其中“pos”将是应该添加“value”值的位置。如果要插入的位置无效,即超过当前列表的大小,则必须返回 false。 如果节点被正确添加,则返回 true。 注意:零位对应LinkedList的头部。
我的代码:
LinkedList.prototype.addInPos = function(pos, value) {
if(pos > this.size) {
return false;
}
const newNode = new Node(pos, value);
let current = this.head;
let previous;
if(pos === 0) {
newNode.next = current;
current.prev = newNode;
this.head = newNode;
} else {
for(let i = 0; i < pos; i++){
previous = current;
current = current.next;
}
newNode.next = current;
newNode.prev = previous;
current.prev = newNode;
previous.next = newNode;
}
}
谢谢。
【问题讨论】: