JavaScript单向链表结构:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>单向链表</title>
</head>
<body>
<h1>见控制台打印</h1>
<button id="tian">添加</button>
<button id="yichu">移除</button>
<button id="dayin">打印</button>
<button id="long">长度</button>
<script>
/*链表结构
添加节点:append 查找节点:find 指定数据后添加节点:insert
删除节点:remove 返回length:size
*/
let LinkedList = (function () {
//避免外部访问
let HEAD = Symbol();
//存储数据与next节点的类
class Node {
constructor(data) {
this.data = data; //存储数据
this.next = null; //指向下一节点
}
}
return class {
constructor() {
//数据链头
this[HEAD] = null;
}
//尾部追加数据
append(data) {
//创建对应的链节点
let node = new Node(data);
//获取链头
let head = this[HEAD];
// console.log(head)
// debugger;
//如果是链头 则null
if (head === null) {
this[HEAD] = node;
return;
} else { //如果不是链头
//如果不是链头 循环找到链尾
while (head.next !== null) { //最后一个head.next=null的数据会被赋值给head
//一直把head.next提取出来 直到最后一个数据的next赋值给head
head = head.next;
}
//之后让最后一个head的next等于新添加的node
head.next = node;
}
}
//取值
find(index) {
let head = this[HEAD];
let i = 0;
while (head) {
if (i === index) return head;
head = head.next;
i++;
}
//超出长度返回null
return null;
}
//插入 (index前面插入)
insert(index, data) {
let newNode = new Node(data);
//当前index后面对应的node数据链
let nodeBefore,
nodeAfter = this.find(index);
//考虑index=0的情况
if (index === 0) {
//头等于传进来的数据
this[HEAD] = newNode;
} else {
//获取前一个数据 从而插入到前一个数据后面
nodeBefore = this.find(index - 1);
}
//有往下执行 插入到前一个数据后面
nodeBefore && (nodeBefore.next = newNode);
//尾部接上以前的数据 这样就算是头部插入数据
newNode.next = nodeAfter;
}
//移除
remove(index) {
//当前index后面对应的node数据链
let nodeBefore,
nodeAfter = this.find(index+1);
//考虑index=0的情况
if (index === 0) {
//直接等于0后面的数据
this[HEAD] = nodeAfter;
} else {
//获取前一个数据 从而插入到前一个数据后面
nodeBefore = this.find(index - 1);
nodeBefore.next = nodeAfter;
}
}
//打印
print() {
let head = this[HEAD],
arr = [];
while (head){
arr.push(head.data);
head = head.next;
}
return arr;
}
//长度
size() {
let i=0,
head = this[HEAD];
while(head){
head = head.next;
i++;
}
return i;
}
}
})();
let linked = new LinkedList;
//存数据
linked.append("派大星0");
linked.append("派大星1");
linked.append("派大星2");
//查看数据
console.log(linked);
//取值
console.log(linked.find(1));
//插入
tian.onclick = function () {
linked.insert(1, '海绵宝宝');
console.log(linked);
}
//移除
yichu.onclick = function () {
linked.remove(1);
console.log(linked);
}
//打印
dayin.onclick = function () {
console.log(linked.print());
}
//长度
long.onclick = function () {
console.log(linked.size());
}
</script>
</body>
</html>