【问题标题】:Whats wrong with my LinkedList remove method我的 LinkedList 删除方法有什么问题
【发布时间】:2017-02-16 06:30:54
【问题描述】:

我的删除功能出了什么问题, 我可以删除头部,但不能删除任何其他节点。

SLinkedList.prototype.remove = function(value) {
  if(!this.findValue(value) )return;
  if(this.head.value === value){
    this.head = this.head.next;
    return;
  }
  var prev = null;
  var cur = this.head;
  while(cur.value !== value){
    prev = cur;
    cur = cur.next
  }
  prev.next = cur.next;
}

这是一个完整的 javascript 实现的链接 repl it

【问题讨论】:

  • 上面的代码似乎对应于SLinkedList.prototype.findValue而不是SLinkedList.prototype.remove
  • 该函数正在检查该值是否存在于该链表中。你可以点击“repl it”链接查看完整的实现
  • 好吧...您的删除方法(每个代码)仅删除 head 值或 head.next 值(如果您修复条件以检查 this.head.next.value === 值)。但它并没有更进一步。所以也许你想首先遍历列表并找到元素,其中 next.value 是值。
  • 谢谢刚刚发现我输入错了,剪掉了,改了

标签: javascript data-structures linked-list


【解决方案1】:

您的fineValue() 方法中有两个错误。首先,您的 while 循环正在查看 this.head ,它永远不会改变。其次,您在第一次迭代后返回 false。希望这可以帮助。

SLinkedList.prototype.findValue = function(value) {
 if (!this.head) return false
  var cur = this.head;
  while (cur) { //Need to check cur not this.head
   if (cur.value === value) {
    return true
   }
   cur = cur.next
   //return false; //Move this out of the while loop
 }
 return false
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-14
    相关资源
    最近更新 更多