function Node(item) {
this.item = item;
this.next = null;
}
function LinkedList() {
this.length = 0;
this.head = null;
}
// 添加元素到链表尾部
LinkedList.prototype.append = function(item) {
if (this.length === 0) {
this.head = item;
} else {
var current = this.head;
while(current.next) {
current = current.next;
}
current.next = item;
}
this.length++;
}
// 向单向链表中某个位置插入元素
LinkedList.prototype.insert = function(position, item) {
if (position === 0) {
var current = this.head;
this.head = item;
this.head.next = current;
} else {
var current = this.head;
var prevent = current;
var index = 0;
while(position > index) {
prevent = current;
current = current.next;
index++;
}
item.next = current;
prevent.next = item;
}
this.length++;
}
// 寻找某个元素在单向链表中的位置
LinkedList.prototype.indexOf = function(item) {
var current = this.head;
var index = 0;
while(current.next) {
if (current.item === item) {
return index;
}
current = current.next;
index++;
}
return -1;
}
// 移除给定的元素
LinkedList.prototype.remove = function(item) {
var current = this.head;
var prevent = current;
var index = 0;
while(current.next) {
if (current.item === item) {
if (index === 0) {
this.head = current.next;
} else {
prevent.next = current.next;
}
this.length --;
return;
}
prevent = current;
current = current.next;
index ++;
}
if (current.item === item) {
prevent.next = null;
this.length--;
}
}
// 移除单向链表中某个位置的元素
LinkedList.prototype.removeAt = function(position) {
var current = this.head;
var prevent = current;
var index = 0;
while(current.next) {
if (position === index) {
if (index === 0) {
this.head = current.next;
} else {
prevent.next = current.next;
}
this.length --;
return;
}
prevent = current;
current = current.next;
index ++;
}
if (position === index) {
prevent.next = null;
this.length --;
}
}
// 获取单向链表的头部
LinkedList.prototype.getHead = function() {
return this.head;
}
// 检查单向链表是否为空,为空则返回true
LinkedList.prototype.isEmpty = function() {
return this.length === 0;
}
// 将链表所有内容以字符串输出
LinkedList.prototype.toString = function() {
var current = this.head;
var content = current.item.toString();
while(current.next) {
current = current.next;
content += current.item.toString();
}
return content;
}
// 返回单向链表长度
LinkedList.prototype.size = function() {
return this.length;
}
var n1 = new Node(9);
var n2 = new Node(8);
var n3 = new Node(6);
var l = new LinkedList();
l.append(n1);
l.append(n2);
l.insert(1, n3);
console.log(l.toString());
console.log(l.indexOf(6));
l.remove(8);
console.log(l.toString());
// l.insert(0, n1);
// console.log(l.toString());
// l.removeAt(2);
// console.log(l.toString());
// console.log(l.getHead());
// console.log(l.isEmpty());
// console.log(l.size());
console