recently, I have been looking at the JavaScript description of data structure and algorithm. I have encountered some problems in the chapter of linked list. The description of the problem is as follows
to delete the item node from the linked list, prevNode is the previous node of the item node
the book uses prevNode.next = prevNode.next.next; to change the direction of the linked list.
but my understanding is prevNode.next = item , and then try to delete the linked list using prevNode.next = item.next, but the result is tantamount to breaking the linked list, leaving only the prevNode and the previous node.
I hope all the gods can answer their questions. Thank you very much.
< hr >Thank you for the sad correction of changing the name. Here is the code in the book
//Node
function Node(element){
this.element = element;
this.next = null;
}
//LinkedList
function LList(){
this.head = new Node("head"); //headnextnull,nextnext
this.find = find;
this.findPrevious = findPrevious;
this.insert = insert;
this.remove = remove;
this.display = display;
}
function find(item){
var currNode = this.head;
while(currNode.element != item){
currNode = currNode.next;
}
return currNode;
}
function insert(newElement,item){
var newNode = new Node(newElement);
var current = this.find(item);
newNode.next = current.next;
current.next = newNode;
}
//removeitemnode
function findPrevious(item){
var currNode = this.head;
while(!(currNode.next==null) && (currNode.next.element!=item)){
currNode=currNode.next;
}
return currNode;
}
function remove(item){
var prevNode = this.findPrevious(item);
if(!(prevNode.next==null)){
prevNode.next = prevNode.next.next; //-sharp-sharp-sharp-sharp-sharp-sharp-sharp-sharp-sharp-sharp-sharp
}
}
function display(){
var currNode = this.head;
while(!(currNode.next==null)){
console.log(currNode.next.element); //current.next.element
currNode = currNode.next;
}
}
//
var cities = new LList();
cities.insert("","head");
cities.insert("","");
cities.insert("","");
cities.insert("","");
cities.display()
console.log(cities.find(""))
cities.remove("");
cities.display();
console.log(cities.find("head"))
the result of the output at this time is
remove()prevNode.next = prevNode.next.next;
prevNode.next = item.next;