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 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿