JS Analog link List

Source: Internet
Author: User

Linked list: Each element has a pointer that points to the next element

Linked list var head = Null;length = 0;class linkedlist{constructor () {}append (ele) {var cnode = {Ele:ele,next:null};if (head = = = Nu ll) {head = Cnode;} else{//Append to node var current = Head;while (current.next) {current = Current.next;} Current.next = Cnode;} length++;} RemoveAt (POS) {//Remove elements//Check out of Bounds if (pos >-1 && pos < length) {var current = Head,previous,index = 0;//Removes the first item if (p OS = = 0) {head = Current.next;} Else{while (index++ < pos) {previous = Current;current = Current.next;} The previous next, which points to next on the current item, kills the current item previous.next = Current.next;} Length--;return Current.ele;} Else{return null;}} Insert (Pos,ele) {if (pos >= 0 && pos <= length) {var nodes = {Ele:ele,next:null};var current = Head,previous,in Dex = 0;if (pos = = 0) {//First insert Nodes.next = Current;head = nodes;} Else{while (index++ < pos) {previous = Current;current = Current.next;} Nodes.next = Current;previous.next = nodes;} Length++;return true;} Else{return false;}}  IndexOf (ele) {var current = Head;var index = -1;while (current) {if (Current.ele = = =Ele) {return index;} Index++;current = Current.next;} return index;} Remove (ele) {var index = this.indexof (ele); return this.removeat (index);}   ToString () {var current = Head;var str = ', var index = 0;while (current) {str = str + current.ele+ "-" + index + "\ n"; Index++;current = Current.next;} Console.log (str);} Size () {return length;} IsEmpty () {return!length;} GetHead () {return head;}} var list = new LinkedList (), List.append ("a"), List.append ("B"), List.append ("C"), List.insert (2, "BGB"), List.append ("D "); list.tostring ();

  

JS Analog link 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.