单向链表(单链表)是链表的一种,其特点是链表的链接方向是单向的,对链表的访问要通过顺序读取从头部开始。
javascript实现单向链表代码如下:
function LinkedList() {
var Node = function (element) { //表示要加入列表的项,next属性指向下一个节点项的指针
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) {//while循环寻找最后元素
current = current.next;
}
current.next = node;
}
length++;//更新列表的长度
};
this.insert = function (position, element) {//在任意一个位置插入一个元素,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;
if (position === 0) {
head = current.next;
} else {
while (index++ < position) {
previous = current;
current = 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 = -1;
while (current) {
index++;
if (element === current.element) {
return 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.getHead = function () {//获得head
return head;
};
}
var list = new LinkedList();
list.append(15);
list.append(8);
list.append(12);
list.append(10);
list.append(6);
console.log("链表是否为空?" + list.isEmpty());
console.log("链表长度:" + list.size());
console.log(list.toString());
console.log(list.indexOf(10));
|