function ListNode(val) {
this.val = val;
this.next = null;
}
class LinkList {
constructor() {
this.length = 0;
// 头部指针
this.head = null;
// 尾部指针
this.last = null;
}
createNode(value) {
return new ListNode(value);
}
append(value) {
const newNode = this.createNode(value);
if (!this.head) {
// 是第一个列表元素
this.head = newNode;
this.last = newNode;
this.length++;
} else {
// 不是第一个元素,添加到列表末尾
this.last.next = newNode;
this.last = newNode;
}
this.length++;
}
insert(value, index) {
const newNode = this.createNode(value);
if (index === 0) {
// 在头部插入
newNode.next = this.head;
this.head = newNode;
} else if (index === this.length) {
// 在尾部插入
this.last.next = newNode;
this.last = newNode;
} else {
// 在中间位置插入
let beforeNode = this.find(index - 1);
newNode.next = beforeNode.next;
beforeNode.next = newNode;
}
this.length++;
}
find(index) {
let current = this.head;
if (index > this.length) {
return new Error("out of range");
} else if (index === 0) {
return this.head;
} else if (index === this.length) {
return this.last;
}
while (index > 0 && index < this.length) {
current = current.next;
index--;
}
return current;
}
delete(index) {
if (index === this.length - 1) {
node.next = null;
this.last = node;
} else if (index === 0) {
this.head.next = null;
this.head = this.head.next;
} else {
let node = this.find(index - 1);
node.next = node.next.next;
node.next.next = null;
}
this.length--;
}
displayList() {
let current = this.head;
while (current.next) {
console.log(current);
current = current.next;
}
}
}
const list = new LinkList();
list.append({ name: "我是一" });
list.append({ name: "我是小马" });
list.append({ name: "我是小鸡" });
list.append({ name: "我是小鸭" });
list.append({ name: "我是小鱼" });
list.insert({ name: "小插" }, 2);
list.displayList();
console.log(list.length);
console.log(list.find(2));
javaScript单链表
于 2022-03-25 18:13:56 首次发布