function NodeList() {
this.head = null;
this.length = 0;
function Node(data) {
this.data = data;
this.next = null;
}
//保存当前节点
var curren = null;
//1.末尾增加节点操作
NodeList.prototype.append = function (data) {
var node = new Node(data);
if (this.length == 0) {
this.head = node;
//更新节点
curren = node;
this.length++;
} else {
curren.next = node;
//更新节点
curren = node;
this.length++;
}
};
//2.指定位置插入操作
NodeList.prototype.inser = function (data, index) {
var inhead = this.head;
var bkhead = null;
var node = new Node(data);
if (index < 0 || index > this.length) {
return false;
}
if (index == 0) {
node = this.head;
this.head = node;
} else {
for (var i = 0; i < index - 1; i++) {
inhead = inhead.next;
}
bkhead = inhead;
inhead = inhead.next;
node.next = inhead;
bkhead.next = node;
this.length++;
}
};
//3.toString方法
NodeList.prototype.toString = function () {
var strhead = this.head;
var str = [];
while (strhead) {
str.push(strhead.data);
strhead = strhead.next;
}
console.log(str.join(""));
};
//4.修改操作
NodeList.prototype.updata = function (data, index) {
var current = this.head;
if (index > this.length - 1 || index < 0) {
return false;
} else {
if (index == 0) {
this.head.data = data;
}
for (var i = 0; i < index; i++) {
current = current.next;
}
current.data = data;
}
};
//5.移除指定位置操作
NodeList.prototype.removeAt = function (index) {
var current = this.head;
if (index > this.length - 1 || index < 0) {
return flase;
} else {
if (index == 0) {
this.head = current.next;
} else {
for (var i = 0; i < index - 1; i++) {
//被删除位置的前一个节点
current = current.next;
console.log(current);
}
current.next = current.next.next;
}
}
this.length--;
};
}
var l = new NodeList();
l.append(1);
l.append(2);
l.append(3);
l.inser("我是你爸爸", 3);
l.updata("你是我儿子", 3);
l.removeAt(2);
console.log(l);
查的方法比较简单就没写