Data structure and algorithm in JavaScript (iii): Linked list

Source: Internet
Author: User
Tags arrays join prev

This article mainly introduces the data structure and algorithm in JavaScript (c): Linked list, this article explains the single linked list and double linked list, and add section and delete section code example, need friends can refer to the following

We can see that the queues and stacks in the JavaScript concept are a kind of special linear table structure, and also a simple array based sequential storage structure. Because the JavaScript interpreter is directly optimized for arrays, there is no problem with the fixed length of the array in many programming languages (it is more difficult to add when the array is filled, including adding deletes, all of which need to transform all the elements of the array into positions. The array of JavaScript is really directly to the optimization, such as the Push,pop,shift,unshift,split method and so on ...)

Linear table of sequential storage structure, the biggest drawback is that changes in the arrangement of one of the elements will cause the whole set of changes, the reason is that in the memory of the storage is coherent without clearance, delete a natural to fill up. In view of the optimization of this structure, a chain-type storage structure appears, 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 the list, in the chain structure, data = (information + address)

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

Array elements are logically referenced by positional relationships, and lists are referenced by saving reference pointer relationships for each data element.

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

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

Linked lists are generally, single linked list, static linked list, circular chain list, two-way linked list

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

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

Circular chain list: Because the single linked list will only be passed back, so when the tail, to go back to the first will be very troublesome, so the chain of the tail section and head to form a cycle

Two-way linked list: For a single list of optimization, so that each section can know who is before and after, so in addition to the pointer field will also have a front pointer field, so as to improve the search efficiency, but brought some in the design of complexity, in general, is the space to change time

In fact, the linked list is a kind of optimization method for sequential storage structure in the linear table, but in JavaScript language because of the particularity of the array (automatically update the reference position), we can do the structure of the linked list storage by the object way.

Single linked list

We implement one of the simplest linked list relationships

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17-18 function Createlinklist () {var _this = {}, prev = null; return {add:function (val) {//save current Reference prev = {Data:val, Next: Prev | | NULL}}} var linkslist = Createlinklist (); Linkslist.add ("Arron1"); Linkslist.add ("Arron2"); Linkslist.add ("Arron3"); The next chain in the node section is-arron3-arron2-arron1.

Using the node object's next to refer directly to the next node object, the first is achieved through a list of references, this chain of thought in the asynchronous deferred of the then method, as well as Japan's cho45 Jsderferre are useful. One of the most critical issues with this implementation is how do we insert data dynamically after the execution section?

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

?

1 2 3 4 5 6 7 8 9 10 Find the corresponding section var findnode = function Createfindnode (currnode) {return function (key) {//loop to find the executed section, if not returning itself while (Currnode . Data!= key) {currnode = Currnode.next;} return currnode; }} (Headnode);

This is a way to find the current section, by passing the original header Headnode section and looking down to next until you find the corresponding section information

This is accomplished using the Curry method.

So when inserting the section, the conversion relationship for the list address is this way

A-b-c-d in the 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.

Add section by Insert method

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 Create a section function CreateNode (data) {this.data = data; this.next = null;}//Initialize header//Start form a chain from Headnode//join Var Headno via next   de = new CreateNode ("Head"); Find the corresponding section var findnode = function Createfindnode (currnode) {return function (key) {//loop to find the executed section, if not returning itself while (Currnode . Data!= key) {currnode = Currnode.next;} return currnode;   }} (Headnode); Insert a new section This.insert = function (data, key) {//Create a new section var NewNode = CreateNode (data)//////////////////////////////(////) Current = Findnode (key); Inserts a new connection, changes 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 beginning of the section.

In the Insert Add section method, through a search 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?

Because of the specificity of the linked list, we a->b->c->d that 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 kind of like a DOM operation. RemoveChild finds its parent node call remove child node

In the same way, we also need to design a traversal to backtrack a parent node in the design of the Remove method.

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 Found 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 Method This.remove = function (key) {var prevnode = findprevious (key); if (!) ( Prevnode.next = = null) {//Modify the linked list relationship prevnode.next = PrevNode.next.next;};

Test code:

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30-31 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 <!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 a linked list/ ///////////function createlinklist () { //create section function CreateNode (data) {this.data = data; this.next = null;} &N Bsp Initialize the head section//from Headnode start to form a chain//link through next to the var headnode = new CreateNode ("Head");  //find the corresponding section var findnode = function Createfindnode (currnode) {return function (key) {//loop to find the executed section if not returning itself while (c Urrnode.data!= key) {currnode = Currnode.next;} return currnode; }} (Headnode);  //Find 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 = CreateNode (data); After putting the new added into the var current = Findnode (key); Inserts a new connection, changes the reference relationship//1:a-b-c-d//2:a-b-n-c-d newnode.next = Current.next; Current.next = NewNode; };  //Insert Method This.remove = function (key) {var prevnode = findprevious (key); if (!) ( Prevnode.next = = null) {//Modify the linked list relationship prevnode.next = PrevNode.next.next;};     This.display = function (fn) {var currnode = Headnode; 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.creat Eelement (' 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 a single list, which is to add a pointer to each section of the list.

Add section

?

1 2 3 4 5 6 7 8 9 10 11-12 Insert a new section This.insert = function (data, key) {//Create a new section var NewNode = CreateNode (data)//////////////////////////////(////) Current = Findnode (Headnode,key); Inserts a new connection, changes the reference relationship Newnode.next = Current.next; Newnode.previous = Current Current.next = NewNode; };

Delete a section

?

1 2 3 4 5 6 7 8 9 This.remove = function (key) {var currnode = Findnode (Headnode,key); if (!) ( Currnode.next = = null)) {currNode.previous.next = Currnode.next; currNode.next.previous = currnode.previous; Currnode.next = null; currnode.previous = null; } };

There is an obvious optimization in the delete operation: There is no need to find the parent section, because doubly-linked lists are more efficient than single chains because they are doubly referenced.

Test code:

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26-27--28 29---30 31--32 33 34 35 36 37 38-39 40 41 42 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 5 86 87 88 89 90 <!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 List////////////function createlinklist () { //create section function CreateNode (data) {this.data = data; This.next = nul L this.previous = null}  //Initialize header///Start form a chain from Headnode//next join var Headnode = new CreateNode ("Head");  //Find the corresponding data in the list var findnode = function (Currnode, key) {//loop to find the executed section if it does not return itself while (Currnode.data!= key) {Currnode = Currnode.next; return currnode;  //Insert a new section This.insert = function (data, key) {//Create a new section var NewNode = CreateNode (data);////////////// To hang in var current = Findnode (Headnode,key); Inserts a new connection, changes the reference relationship Newnode.next = Current.next; Newnode.previous = Current Current.next = NewNode; };   This.remove = function (key) {var currnode = Findnode (Headnode,key); if (!) ( 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.creat Eelement (' 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>
Related Article

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.