Home > Web Front-end > JS Tutorial > body text

Create a linked list using js objects

高洛峰
Release: 2016-10-08 14:57:09
Original
1720 people have browsed it

//The following is a linked list class

function LinkedList(){


//Node represents the item to be added to the list
var Node=function(element){

<br/>
Copy after login

 this.element=element;
 this.next= null;
};

var length=0;//Storage the number of list items
var head=null;//head stores a reference to the first node

//Append elements to the end of the linked list
this. append=function(element){
 var node=new Node(element),
 current;

if(head===null){
 head=node;

 }else{
 current=node;

 while( current.next){
   current=current.next;
  }

  current.next=node;

  }

 length++;
};

//Insert an element at any position in the linked list
this.insert=function (position,element){
 if(position>=0&&position<=length){<br/><br/> var node=new Node(element),<br/>  current=head,<br/>  previous,<br/>  index=0;<br/><br/> if(position=== 0){<br/>   node.next=current;<br/>  head=node;<br/><br/>  }else{<br/>  while(index-1 && position  var current=head,
  previous,
  index=0;

  if(position===0){
  head=current.next;
  } else{

  while(index   previous=current;
  current=current.next;
   index++;
   }
   previous.next=current.next;

  }

 length--;

  return current .element;
 }else{
  return null;
  }
};

//Return the position of the element in the linked list
this.indexOf=function(element){
 var current=head,
 index=-1;
U While (Current) {
if (Element === Current.element) {
Return Index;
}
Index ++;
Current = Current.next; / / Remove an element
this.remove=function(element){

 var index=this.indexOf(element);

 return this.removeAt(index);
};

//Judge whether the linked list is empty

this .isEmpty=function(){
 Return length===0;
};

//Return the length of the linked list
this.size=function(){
return length;
};

//Convert the LinkedList object into a string

this.toString=function(){

 var current=head,
 string="";

 while(current){
  string=current.element;

  current=current.next;

 }

return string;

};

};

var list=new LinkedList();
list.append(15);
list.append(10);
list.insert(1,11);

list.removeAt (2)

console.log(list.size());



Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template