function Linkedlist(){
var Node = function(element){
this.element = element;
this.next = null;
};
var length = 0;
var head = null;
this.append = function(element){
var node = new Node(element),
current;
if(head ===null){
head = node;
}else{
current = head;
while(current.next){
current = current.next;
}
current.next = node;
}
length++;
};
this.insert = function(position,element){
//检查越界
if( position >=0 && position <= length){
var node = new Node(element),
current = head,
previous,
index = 0;
if(position === 0){
node.next = current;
head = node;
}else{
while(index++ < position){
previous = current;
current = current.next;
}
node.next = current;
previous.next = node;
}
length++;
return true;
}else{
return false;
}
};
this.removeAt = function(position){
//检查越界值
if(position>-1 && position <length){
var current = head, //对列表当前元素的引用
previous, //对当前元素的前一个元素的引用
index=0; //用于内部控制和递增
//移除第一项,让head指向第二个元素
if(position === 0){
head = current.next;
}else{
while(index++ < position){
previous = current;
current = current.next;
}
//将previous与current的下一项连接起来;跳过current,从而移除它
previous.next = current.next;
}
length--;
return current.element;
}else{
return null;
}
};
this.remove = function(element){
var index = this.indexOf(element);
return this.removeAt(index);
};
this.indexOf = function(element){
var current = head,
index = 0;
while(current){
if(element === current.element){
return index;
}
index++;
current = current.next;
}
return -1;
};
this.isEmpty = function(){
return length ===0;
};
this.size = function(){
return length;
};
this.toString = function(){
var current = head,
string = ''; //用于拼接元素值
while(current){ //循环访问列表中的每个元素
string += current.element;
current = current.next;
}
return string;
};
this.print = function(){
console.log(list.toString());
};
this.getHead = function(){
return head;
}
}
var list = new Linkedlist();
list.append(1);
list.append(2);
list.append(3);
list.insert(1,'我是插入的元素');
list.removeAt(2);
console.log(list.indexOf(1));
list.remove(2);
console.log(list.getHead());
list.print();
根据书上的代码改了两个地方:
1)字符串输出toString(),要使链表从头到尾每个元素输出,应该用+=:
string += current.element;
2)indexOf()位置应该是从0开始:
index = 0;