JavaScript implements a one-way linked list

Source: Internet
Author: User

JavaScript itself provides a very useful data type to meet the daily use of everyone. Array and Object alone are sufficient to cope with most of the daily needs, which also leads to a lot of front-end ER on the data structure of this piece is not very understanding.

The data structure is a compulsory subject of CS, the front end of this circle is not a high proportion of children's shoes, I believe many people do not know much about the data structure. Although I read the university is also CS, but at that time classes are basically sleeping, data structure is also learning a mess, and now basically completely forget.

Let's take a look at how JavaScript can be used to implement a one- way list.

In Wikipedia, the list is described as follows:

A linked list (Linked list) is a common basic data structure, a linear table, but does not store data in a linear order, but rather as a pointer to the next node (Pointer) in each node. Since they do not have to be stored sequentially, the list can achieve an O (1) complexity at the time of insertion, much faster than another linear table-order table, but the time to find a node or to access a particular number of nodes requires O (n), while the corresponding time complexity of the sequential table is O (logn) and O (1) respectively.

From this you can see that the list and the data, compared with a few advantages:

    1. There is no need to pre-allocate memory (in static languages, arrays are pre-allocated memory space and cannot be changed after space allocation). )
    2. Inserting and deleting elements does not need to move the rest of the elements, more efficiently

JavaScript acts as a dynamic language in which arrays are dynamic arrays and do not require pre-allocated memory. The array length can also be dynamically added and subtracted in the process, which directly extends the application range of the array type.

Arrays are a very cumbersome thing to do when inserting and deleting elements, but this is the advantage of the list. In terms of the efficiency of finding elements, the list is less convenient and faster than an array.

One-way linked list is the simplest of the list, which is characterized by the link direction of the linked list is unidirectional, access to the linked list is to be read sequentially from the head.

Let's look at the diagram of the unidirectional list:

As you can see, each item (element) in a list has two parts: data and next. Where data is used to store the information and is the true storage area. And next is used to store the address to point to the next item.

Let's look at how to design a one-way list.

A generic one-way list has the following properties and methods:

    • First: point to item one
    • Last: Point to final item
    • Length: The item number of the linked list
    • Get (): Gets the item at the specified location
    • Set (): Modifies the item at the specified location
    • Add (): Inserts a new item to the specified location
    • Remove (): Removes the item at the specified location
    • Clear (): Empty all item

For convenience, some syntactic sugars are also available:

    • AddFirst (): Insert a new item into the list header
    • AddLast (): Insert a new item to the tail of the list
    • Removefirst (): Remove the first item
    • Removelast (): Remove Last item
    • ToString (): The list is output as "3.14"

The following is the Singlylinkedlist class:

varSinglylinkedlist =function () {    functionsinglylinkedlist () { This. length = 0;  This. First =NULL;  This. Last =NULL; }    /** * Get Item * @param {number} index linked list indexed by index * @returns {*}*/SinglyLinkedList.prototype.get=function(index) {if(typeofIndex!== ' number ' | | Index < 0 | | Index >= This. Length) {            returnundefined; }        varitem = This. First;  for(vari = 0; I < index; i++) {Item=Item.next; }        returnitem;    }; /** * The contents of the item are set according to the index * @param {number} index linked list * @param {*} value needs to be set @retur NS {*}*/SinglyLinkedList.prototype.set=function(Index, value) {if(typeofIndex!== ' number ' | | Index < 0 | | Index >= This. Length) {            return false; }        varitem = This. Get (index); Item.data=value; returnitem;    }; /** * Insert a new item according to the index location * @param {number} index linked list * @param {*} value needs to be set to the values * @retur NS {*}*/SinglyLinkedList.prototype.add=function(Index, value) {if(typeofIndex!== ' number ' | | Index < 0 | | Index > This. length | | index = = =undefined) {            return false; }        varitem ={data:value, Next:NULL        }; if( This. length > 0) {            if(Index = = 0) {Item.next= This. First;  This. First =item; } Else if(Index = = = This. Length) {                 This. Last.next =item;  This. Last =item; } Else {                varPrevitem = This. Get (Index-1), Nextitem= This. Get (index); Item.next=Nextitem; Previtem.next=item; }        } Else {             This. First =item;  This. Last =item; }         This. length++; returnitem;    }; /** * Delete Item according to index * @param {number} index linked list * @returns {Boolean}*/SinglyLinkedList.prototype.remove=function(index) {if(typeofIndex!== ' number ' | | Index < 0 | | Index >= This. Length) {            return false; }        varitem = This. Get (index); if( This. length > 1) {            if(Index = = 0) {                 This. First =Item.next; } Else if(Index = = = This. length-1) {                 This. Last = This. Get ( This. length-2);  This. Last.next =NULL; } Else {                 This. Get (index-1). Next =Item.next; }        } Else {             This. First =NULL;  This. Last =NULL; } Item=NULL;  This. length--; return true;    }; /** * Empty the entire single linked list * @returns {Boolean}*/SinglyLinkedList.prototype.clear=function () {         This. First =NULL;  This. Last =NULL;  This. length = 0; return true;    }; SinglyLinkedList.prototype.addFirst=function(value) {return  This. Add (0, value);    }; SinglyLinkedList.prototype.addLast=function(value) {return  This. Add ( This. length, value);    }; SinglyLinkedList.prototype.removeFirst=function () {        return  This. Remove (0);    }; SinglyLinkedList.prototype.removeLast=function () {        return  This. Remove ( This. length-1);    }; SinglyLinkedList.prototype.toString=function () {        vararr =[], item= {}; if( This. Length) {             Do{Item= Item.next | | This. Get (0); Arr.push (typeofItem.data = = = ' object '? Json.stringify (item.data). Replace (/\ "/g,"): Item.data); }  while(Item.next); }        returnArr.join ('-a ');    }; returnSinglylinkedlist;} ();

The way to use it is simple:

varSList =Newsinglylinkedlist (); Slist.addlast (A); Slist.addfirst (10); Slist.addlast (3.14); Slist.add (2, [1, 2]); Slist.addlast ({a:1, B:2}); Console.log (slist.tostring ()); //{a:1,b:2}, 3.14, aConsole.log (slist.length);//5Slist.removefirst (); Slist.removelast (); Console.log (slist.tostring ()); //"A--[3.14]"Console.log (slist.length);//3

Resources:

Http://zh.wikipedia.org/wiki/%E9%93%BE%E8%A1%A8

Http://www.cnblogs.com/skywang12345/p/3561803.html#a33

This article Maple Jan

This article link: http://www.cnblogs.com/maplejan/p/3903749.html

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.