使用 JavaScript 实现链表

时间:2023-03-09 07:38:11
使用 JavaScript 实现链表

代码:

 <!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body></body>
<script>
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.removeAt = function(position) {
if (position > -1 && position < length) {
var current = head,
previous,
index = 0; //移除第一项
if(position == 0) {
head = current.next;
return current.element;
}else{
while(index++ < position){
previous = current;//删除指定位置前的一个元素
current = current.next;
}
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.insert = function(position, element) {
if(position > -1 && 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;
}
}; //找到并返回一个元素的位置,如果元素不存在,返回-1
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.slice(1);
}; //返回链表中第一个元素
this.getHead = function() {
return head;
}; //查看链表(中的元素和指针,以数组形式输出)
this.print = function() {
var current = head,
list = []; while(current) {
list.push(current);
current = current.next;
}
return list;
};
} var list = new LinkedList();
list.append(5);
list.append(10);
list.append(7);
list.append(9);
list.append(100);
list.append(-2);
console.log(list.toString());
console.log(list.print());
console.log(list.indexOf(115));
console.log(list.indexOf(5));
console.log(list.indexOf(7));
console.log(list.isEmpty());
console.log(list.size());
console.log(list.getHead()); console.log(list.removeAt(0));
console.log(list.toString());
console.log(list.removeAt(1));
console.log(list.toString()); list.insert(0, 500);
console.log(list.toString());
</script>
</html>

输出:

使用 JavaScript 实现链表