append() 在链表后添加节点
// 定义链表
// 同样使用 ES6 class 和立即执行函数
let LinkedList = (function() {
// 定义一个链表
class Node {
// 初始化链表
constructor(element) {
this.element = element;
this.next = null;
}
}
// 定义链表初始化值
let length = new WeakMap(); // 初始时,链表的长度
let head = new WeakMap(); // 初始时, 链表的头部
// 返回的链表
return class LinkedList {
constructor() {
// 初始化
length.set(this, 0);
head.set(this, null);
}
// 链表的方法
// append 在链表最后添加节点
append(element) {
// 创建节点
let node = new Node(element),
// 声明一个变量, 用于获取链表的位置
current;
// 判断链表是否有数据
if (this.getHeader() === null) {
// 当链表为空的情况下
head.set(this, node); // 直接添加
} else {
// 链表头部不为空
// 找到链表最末的节点, 让最末的节点的 next 指向添的node
current = this.getHeader(); // 获取 head
// 判断当前节点的next存在
while (current.next) {
// next ++ ,一直循环
current = current.next;
}
// 进行while循环完后,current 就为最后的节点。
// 然后进行赋值
current.next = node;
// 赋值后,让链表长度 +1
// 使用size获取链表的长度
let l = this.size();
l++; // 让链表的长度加一
length.set(this, l); // 重新赋值
// 追加后,返回head, 查看head
console.log(this.getHeader());
}
}
// 判断链表的头部
getHeader() {
return head.get(this);
}
// 返回链表的长度
size() {
return length.get(this);
}
}
})();
let list = new LinkedList();
list.append(0);
list.append(1);
list.append(2);
list.append(3);
/*
* 输出this.getHeader() 能够查看到链表的情况
*/
输出结果