Home  >  Article  >  Web Front-end  >  Create a linked list using js objects

Create a linked list using js objects

高洛峰
高洛峰Original
2016-10-08 14:57:091065browse

//The following is a linked list class

function LinkedList(){


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

<br/>

 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&&position643259235a5fb7b06618e6bbbb037e52-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());



Statement:
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