1. Concept
The previous blog post we talked about the list, where a method remove () is a temporary comment, this method is a bit complicated, you need to add a previous () method to find the element to delete the previous node, this blog post we analyze the Remove () method.
When you delete a node from a linked list, you need to find the node in front of the node you want to delete. After locating this node, modify its next property to point to the next node to be deleted, so that the deleted node is deleted, is it simple? But the question is, are we going to find the front node of the node to be deleted? This requires adding a findprevious () method to do the job.
The FindPrevious () method iterates through the elements in the linked list, checking that the next node of each node stores the data to be deleted. If found, returns the node (that is, the previous node) so that it can modify its next property. The FindPrevious () method is defined as follows:
function findprevious (item) { var currnode = This . Head; while null) && (currNode.next.element! = Item)) {= currnode.next ; } return Currnode;}
With this findprevious () method, you can consider how to write the Remove () method. The code is as follows:
function Remove (item) { varthis. findprevious (item); if NULL { = preNode.next.next; }}
There is a sentence in this method prenode.next = PreNode.next.next; This uses the object properties in JavaScript, which looks a bit odd, but it makes sense.
2. Code implementation
The following is the complete code and the test code:
functionNode (Element) { This. Element =element; This. Next =NULL;}functionllist () { This. Head =NewNode (' head '); This. Find =find; This. Insert =Insert; This. findprevious =findprevious; This. remove =remove; This. display =display;}functionFind (item) {varCurrnode = This. Head; while(Currnode.element! =Item) {Currnode=Currnode.next; } returnCurrnode;}//Insert an elementfunctionInsert (newelement, item) {varNewNode =NewNode (newelement); varCurrent = This. Find (item); Newnode.next=Current.next; Current.next=NewNode;}functionfindprevious (item) {varCurrnode = This. Head; while((Currnode.next! =NULL) && (currNode.next.element! =item)) {Currnode=Currnode.next; } returnCurrnode;}functionRemove (item) {varPrenode = This. findprevious (item); if(Prenode.next! =NULL) {Prenode.next=PreNode.next.next; }}functiondisplay () {varCurrnode = This. Head; while(! (Currnode.next = =NULL) {document.write (currNode.next.element+ ' '); Currnode=Currnode.next; }}//Test ProgramvarCities =Newllist (); Cities.insert ("Conway", "head"); Cities.insert ("Russellville", "Conway"); Cities.insert ("Carlise", "Russellville"); Cities.insert ("Alma", "Carlise"); Cities.display ();d Ocument.write (' <br> '); Cities.remove (' Carlise '); Cities.display ();
The final output results are as follows:
Linked list structure in JavaScript-remove elements from linked list