Data structures and Algorithms JavaScript (three) linked list

Source: Internet
Author: User

Data structures and Algorithms JavaScript (three) linked list

We can see that the queue and stack in the JavaScript concept is a special linear table structure and a simple array-based sequential storage structure. Since JavaScript's interpreter is directly optimized for arrays, there is no problem with fixed-length arrays in many programming languages (it is difficult to add them when the array is filled up, including adding deletes, all of which need to transform all the elements in the array, The array of JavaScript is really directly optimized, such as the Push,pop,shift,unshift,split method and so on ...)

Linear table of sequential storage structure, the biggest drawback is to change the arrangement of one of the elements will cause the entire collection of changes, the reason is that in memory is a coherent and no gap, delete a nature to fill up. The structure of the optimization after the emergence of a chain storage structure, a different idea, we do not care about the arrangement of data, we only need to put the next data in each element of the location of the record can be, so the link to store the linear table referred to as linked list, in the chain structure, the data = (information + address)

Chain structure, we can also call the address "chain", a data unit is a node, then you can say that the linked list is a set of nodes composed of a collection. Each node has a data block reference to its next node

An array element is a logical reference to a positional relationship, and a linked list is referenced by holding a reference pointer relationship for each data element.

This structural advantage is very obvious, inserting a data at all does not need to care about its arrangement, as long as the "chain" point of convergence

So the idea of the list is not confined to the array, we can use the object, as long as there is a reference relationship between the objects can be

List of links, single linked list, static linked list, circular link list, doubly linked list

Single linked list: is a very single downward transfer, each node only records the next node of information, and the Infernal Affairs in the same way as Tony Leung undercover is through the intermediary line and offline contact, once the middleman broke, then can not prove their identity, so the end has a sentence: "I am a good person, who knows?" ”

Static linked list: is a linked list that is described with an array. That is, each of the following tables in the array is a "section" that contains the data and points to the

Circular chain list: Because the single-linked list will only be passed back, so to reach the end of the time, to go back to the first will be very troublesome, so the tail section of the chain with the head to form a loop

Doubly linked list: For single-linked list optimization, so that each section can know before and after, so in addition to the back of the pointer field there will be a front pointer field, which improves the efficiency of the search, but brings some complexity in the design, in general, the space to change the time

In fact, the linked list is an optimization method for sequential storage structure in the linear table, but in JavaScript language, because of the particularity of the array (automatically updating the reference location), we can use the object to make the structure of the list storage.

Single linked list

We implement one of the simplest linked list relationships

1functionCreatelinklist () {2var _this ={},3 prev =Null;4Return{5 Add:function(Val) {6//Save the current reference { 8  Data:val, 9 Next:prev | | null10 }11 }12 }13 }14 var linkslist =< Span style= "color: #000000;" > Createlinklist (); 15 linkslist.add ("Arron1" ); 16 linkslist.add ("Arron2" ); 17 linkslist.add ("Arron3");          
Node's next chain is-arron3-arron2-arron1.

By referring to the next node object directly through the node object, the first is to implement a reference to the linked list, this chain of thought jquery asynchronous deferred in the then method, as well as the Japanese cho45 Jsderferre are useful. This implementation has one of the most critical issues, how do we dynamically insert data into the execution of the section after?

So we have to design a traversal method that searches for the data on the node chain, and then finds the corresponding data to insert the new section into the current chain and rewrite the location record

12345678910 //在链表中找到对应的节var findNode = function createFindNode(currNode) {    return function(key){        //循环找到执行的节,如果没有返回本身        while (currNode.data != key) {            currNode = currNode.next;        }        return currNode;                    }}(headNode);

This is a way to find the current section by passing the original Headnode section of the head down to find next until the corresponding section information is found

This is accomplished using the Curry method.

So when you insert a section, the conversion relationship for the list address.

a-b-c-d list, if you want to insert an F after C (c.next->d)

A-b-c-f-d, then C,next->f, f.next-d.

Adding a section by using the Insert method

//Create a sectionfunction CreateNode (data) {This.data =DataThis.next =Null;}//Initializing the head section//Form a chain starting from Headnode//Connect through Nextvar Headnode =New CreateNode ("Head");//Find the corresponding section in the listvar FindNode =function Createfindnode (currnode) {Returnfunction (key) {//The loop finds the executed section if it does not return itselfwhile (currnode.data! =Key) {Currnode =Currnode.next; }ReturnCurrnode; }} (Headnode);//Insert a new sectionThis.insert =//  Create a new section var newNode = new  CreateNode (data); // find the corresponding data section in the chain //< Span style= "color: #008000;" > and then put the new join in var current = FindNode (key); // insert a new connection, change the reference relationship // 1: a-b-c-d //2:a-b-n-c-d newnode.next = Current.next; Current.next = NewNode;};          

First, the construction of the CreateNode section is separated, and a header section object is created to initialize the node at the beginning of the initialization.

In the Insert Addition section method, through a lookup of the Headnode chain, find the corresponding section, the new section to add after the last is to modify the relationship between the chain

How do I remove a node from a linked list?

Due to the particularity of the list, we a->b->c->d, if you want to delete C then you must modify B.next->c to B.next->d, so find the previous section to modify its linked list next address, This is a bit like Dom Operation RemoveChild find its parent node call remove child node

The same we also in the design of the Remove method, we need to design a traverse to go back to a parent node can

//Find a previous sectionvar findprevious =function (Currnode) {Returnfunction (key) {while (! ( Currnode.next = = null) && (CurrNode.next.data!) = key) {Currnode = Currnode.next;} return Currnode;}} (Headnode); // Insert method this.remove =< Span style= "color: #000000;" > function (key) {var prevnode = findprevious (key); if (! ( Prevnode.next = = null// Modify the link list relationship Prevnode.next =  PrevNode.next.next;}};          

Test code:

<!doctype Html><button id= "test1" > Insert multiple Data </button><button id= "test2" > Delete russellville data </ Button><div id= "Listshow" ><br/></div><script type= "Text/javascript" >////////////create linked list/ function Createlinklist () {//Create section function CreateNode (data) {this.data = Data;this.next = null;} Initialize the head section//start forming a chain from Headnode//via next link var headnode = new CreateNode ("Head");//find the corresponding section var FindNode = function in the list Createfindnode (currnode) {return function (key) {///loop finds the executed section if it does not return itself while (currnode.data! = key) {Currnode = Currnode.next;} return currnode;}} (headnode);//Find the previous section var findprevious = function (currnode) {return function (key) {while (!) ( Currnode.next = = null) && (currNode.next.data! = key)) {Currnode = Currnode.next;} return currnode;}} (headnode);//Insert a new section This.insert = function (data, key) {//Create a new section var newNode = new CreateNode (data);//find the corresponding section in the Chain// Then put the new join in the var current = FindNode (key);//Insert a new connection, change the reference relationship//1:a-b-c-d//2:a-b-n-c-dnewnode.next = Current.next;curRent.next = newnode;};/ /Insert Method This.remove = function (key) {var prevnode = findprevious (key); Prevnode.next = = null)) {//Modify linked list relationship prevnode.next = PrevNode.next.next;}}; This.display = function (fn) {var currnode = Headnode;while (!) ( Currnode.next = = null)) {Currnode = CURRNODE.NEXT;FN (Currnode.data)}};} var cities = new Createlinklist (), function Create () {var text = '; Cities.display (function (data) {text + = '-' + data;}); var div = document.createelement (' div ') div.innerhtml = Text;document.getelementbyid ("Listshow"). AppendChild (Div)} document.getElementById ("Test1"). onclick = function () {Cities.insert ("Conway", "Head"), Cities.insert ("Russellville "Conway"); Cities.insert ("Carlisle", "Russellville"); Cities.insert ("Alma", "Carlisle"); Create ();} document.getElementById ("Test2"). onclick = function () {Cities.remove ("Russellville"); Create ()}</script>

Double linked list

The principle is the same as the single-linked list, nothing more than to add a pointer to each section of a list of the former chain

Add section

// insert a new section this.insert = //  Create a new section var newNode = new  CreateNode (data); // find the corresponding data section in the chain //< Span style= "color: #008000;" > and then put the new join in var current = FindNode (Headnode,key); // insert a new connection, change the reference relationship newnode.next = Current.next; newnode.previous = current Current.next = NewNode;};   

Delete a section

This.remove = function (key) {    var currnode = FindNode (headnode,key);    null)) {currNode.previous.next = currnode.next; currNode.next.previous =nullnull;}};   

There is an obvious optimization in the delete operation: There is no need to find the parent section because the double-linked list is more efficient than a single chain

Test code:

<!doctype Html><button id= "test1" > Insert multiple Data </button><button id= "test2" > Delete russellville data </ Button><div id= "Listshow" ><br/></div><script type= "Text/javascript" >////////////create linked list/ function Createlinklist () {//Create section function CreateNode (data) {This.data = Data;this.next = Null;this.previous = NULL}//Initialize the head section//Start a chain from Headnode//through Next link var headnode = new CreateNode ("Head"),//find the corresponding data in the list var findNode = function ( Currnode, key) {//loop finds the executed section if it does not return itself while (currnode.data! = key) {Currnode = Currnode.next;} return currnode;} Inserts a new section This.insert = function (data, key) {//Create a new section var newNode = new CreateNode (data);//find the corresponding section in the chain//and put the new join in Var Current = FindNode (Headnode,key);//Insert a new connection, change the reference relationship Newnode.next = Current.next;newnode.previous = Currentcurrent.next = NewNode;}; This.remove = function (key) {var currnode = FindNode (Headnode,key); Currnode.next = = null)) {CurrNode.previous.next = Currnode.next;currnode.next.previous = Currnode.preVious;currnode.next = Null;currnode.previous = null;}}; This.display = function (fn) {var currnode = Headnode;while (!) ( Currnode.next = = null)) {Currnode = CURRNODE.NEXT;FN (Currnode.data)}};} var cities = new Createlinklist (), function Create () {var text = '; Cities.display (function (data) {text + = '-' + data;}); var div = document.createelement (' div ') div.innerhtml = Text;document.getelementbyid ("Listshow"). AppendChild (Div)} document.getElementById ("Test1"). onclick = function () {Cities.insert ("Conway", "Head"), Cities.insert ("Russellville "Conway"); Cities.insert ("Carlisle", "Russellville"); Cities.insert ("Alma", "Carlisle"); Create ();} document.getElementById ("Test2"). onclick = function () {Cities.remove ("Russellville"); Create ()}</script>

git code Download: https://github.com/JsAaron/data_structure.git

Data structures and Algorithms JavaScript (three) linked list

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.