简体   繁体   中英

Whats wrong with my LinkedList remove method

What's wrong with my remove function, I can remove head but cannot remove any other node.

 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; } 

This is a link to full javascript implementation repl it

There are two errors in your fineValue() method. First your while loop was looking at this.head which was never changing. Second you were returning false after the first iteration. Hope this helps.

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
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM