Javascript中的链接列表类
这是LinkedList类的完整实现-
示例
class LinkedList {
constructor() {
this.head = null;
this.length = 0;
}
insert(data, position = this.length) {
let node = new this.Node(data);
if (this.head === null) {
this.head = node;
this.length++;
return this.head;
}
let iter = 1;
let currNode = this.head;
while (currNode.next != null && iter < position) {
currNode = currNode.next;
iter++;
}
node.next = currNode.next;
currNode.next = node;
this.length++;
return node;
}
remove(data, position = 0) {
if (this.length === 0) {
console.log("List is already empty");
return;
}
this.length--;
let currNode = this.head;
if (position <= 0) {
this.head = this.head.next;
}
else if (position >= this.length - 1) {
while (currNode.next.next != null) {
currNode = currNode.next;
}
currNode.next = null;
}
else {
let iter = 0; while (iter < position) {
currNode = currNode.next; iter++;
}
currNode.next = currNode.next.next;
}
return currNode;
}
display() {
let currNode = this.head;
while (currNode != null) {
console.log(currNode.data + " -> ");
currNode = currNode.next;
}
}
}
LinkedList.prototype.Node = class {
constructor(data) {
this.data = data;
this.next = null;
}
};热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下