今天无聊看了看大二的数据结构的书,于是用熟悉的js来写了个单链表,代码如下:
window.onload = function(){
var listArr = [0,1,2,3,4,5];
var list = new LinkList();
for (var i = 0; i < listArr.length; i++) {
list.insert(listArr[i]);
};
list.print();
};
function Node(data){ //节点类
this.next = null;
this.data = data;
}
function LinkList(){ //单链表类
this.head = null; //头节点
this.size = 0; //链表长度
this.insert = function(data,pos){ //插入方法
var newNode = new Node(data);
var tempNode = this.head;
if (this.head == null) {
this.head = newNode;
this.size += 1;
return newNode;
}
if (pos != undefined){
if(pos > this.size || pos < 1) return null;
var n = 1;
while(n < pos-1){
tempNode = tempNode.next;
n++;
}
newNode.next = tempNode.next;
tempNode.next = newNode;
this.size += 1;
return newNode;
}else{
while(tempNode.next != null){
tempNode = tempNode.next;
}
tempNode.next = newNode;
this.size += 1;
return newNode;
}
return null;
};
this.delNode = function(pos){ //删除节点方法
if(pos > this.size || pos < 1) return false;
var tempNode = this.head , n = 1;
this.size -= 1;
if(pos == 1){
this.head = tempNode.next;
return true;
}
while(n < pos-1){
tempNode = tempNode.next;
n++;
}
tempNode.next = tempNode.next.next;
return true;
};
this.getData = function(pos){ //获取节点方法
if(pos > this.size || pos < 1) return null;
var tempNode = this.head , n = 1;
while(n < pos){
tempNode = tempNode.next;
n++;
}
return tempNode.data;
};
this.print = function(){ //打印所有节点数据的方法
var tempNode = this.head;
document.write("The size of the LinkList is " + this.size +"
");
while(tempNode != null){
document.write(tempNode.data + "
");
tempNode = tempNode.next;
}
}
}