【问题标题】:Implement the addInPos method inside the LinkedList prototype in Javascript在 Javascript 中的 LinkedList 原型中实现 addInPos 方法
【发布时间】: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;
  }
 
}

谢谢。

【问题讨论】:

    标签: javascript linked-list


    【解决方案1】:

    理想情况下,insertAt 函数的结构如下所示:

    var insertAt = function(head, item, index) {
        var curr = head;
        var count = 0;
        while (curr !== null) {
            if (count === index) {
                var newNode = { data: item, next: curr.next, prev: curr };
                curr.next = newNode;
                break;
            }
            count++;
            curr = curr.next;
        }
    };
    
    insertAt(head, 2, 3);  
    

    让我知道这是否有效。
    另请查看我创建的这个 LinkedList 类,insertAt 函数目前缺失,但从这个堆栈问题,我也计划将它添加到我的类中。
    Class GitHub
    NPM package - @dsinjs/linked-list
    @ 987654323@

    【讨论】:

    • 嗨 Siddhesh Kulkami,非常感谢您帮助我!
    猜你喜欢
    • 2016-12-12
    • 2019-12-15
    • 1970-01-01
    • 1970-01-01
    • 2020-09-21
    • 2013-04-06
    • 1970-01-01
    • 1970-01-01
    • 2021-09-18
    相关资源
    最近更新 更多