链表中的元素在内存中不必是连续的空间
链表的每个元素由一个存储元素本身的节点和一个指向下个元素的引用组成
链表的常见操作
append(element):向链表的尾部添加新的元素
insert(positon,element):向链表的特定位置添加元素
get(position):获取对应为位置的元素
indexOf(element):返回元素在链表中的索引,没有则返回-1
update(positon,element):修改某个位置的元素
removeAt(positon):从链表的特定位置移除一项
remove(element):从链表中移除一项
isEmpty()
size()
toString()
//单链表
function LinkedList(){
function Node(data){
this.data = data;
this.next = null;
}
this.head = null;
this.length = 0;
LinkedList.prorotype.append() = function(data){
var newNode = new Node(data);
if(this.length == 0){
this.head = newNode;
}else{
var current = this.head;
while(current.next){
current = current.next;
}
current.next = newNode;
}
this.length +=1;
}
LinkedList.prorotype.toString() = function(){
var current = this.head;
var listString = "";
while(current){
listString += current.data + "" ;
current = current.next;
}
return listString;
}
LinkedList.prorotype.insert() = function(positon,data){
if(positon < 0 || positon > this.length){
return false;
}
var newNode = new Node(data);
if(position == 0){
newNode.next = this.head;
this.head = newNode;
}else{
var index = 0;
var current = this.head;
var previous = null;
while(index ++ <position){
previous = current;
current = current.next;
}
newNode.next = current;
previous.next = newNode;
}
this.length +=1;
return true;
}
LinkedList.prorotype.get() = function(positon){
if(positon < 0 ||positon >= this.length){
return null;
}
var current = this.head;
var index = 0;
while(index ++ < positon){
current = current.next;
}
}
LinkedList.prorotype.indexOf() = function(data){
var current = this.head;
var index = 0;
while(current){
if(current.data == data){
return index;
}
current = current.next;
index +=1;
}
return -1;
}
LinkedList.prorotype.update() = function(position,newdata){
if(positon < 0 ||positon >= this.length){
return false;
}
var current = this.head;
var index = 0;
while(index ++ < positon){
current = current.next;
}
current.data = newdata;
return true;
}
LinkedList.prorotype.removeAt() = function(position){
if(positon < 0 ||positon >= this.length){
return null;
}
if(position == 0){
this.head = this.head.next;
}else{
var index = 0;
var current = this.head;
var previous = null;
while(index ++ <position){
previous = current;
current = current.next;
}
previous.next = current.next;
}
this.length -=1;
return current.data;
}
LinkedList.prorotype.remove() = function(data){
var positon = linkedList.indexOf(data)
return this.removeAt(position);
}
LinkedList.prorotype.isEmpty() = function(data){
return this.length ==0;
}
LinkedList.prorotype.size() = function(data){
return this.length;
}
}