function ListNode(val) {
this.val = val;
this.next = null;
this.prev = null;
}
class doubleLinkList {
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;
} else {
this.last.next = newNode;
newNode.prev = this.last;
this.last = newNode;
}
this.length++;
}
insert(value, index) {
const newNode = this.createNode(value);
if (index === 0) {
newNode.next = this.head;
this.head.prev = newNode;
this.head = newNode;
} else if (index === this.length) {
this.last.next = newNode;
newNode.prev = this.last;
this.last = newNode;
} else {
let node = this.find(index);
node.prev.next = newNode;
newNode.prev = node.prev;
newNode.next = node;
node.prev = 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) {
let node = this.find(index);
if (index === this.length - 1) {
this.last = node.prev;
node.prev.next = null;
} else if (index === 0) {
this.head = node.prev;
node.next.prev = null;
} else {
node.prev.next = node.next;
node.next.prev = node.prev;
}
node.next = null;
node.prev = null;
this.length--;
}
displayList() {
let current = this.head;
while (current.next) {
console.log(current);
current = current.next;
}
}
}
const list = new doubleLinkList();
list.append({ name: "我是一" });
list.append({ name: "我是小马" });
list.append({ name: "我是小鸡" });
list.insert({ name: "小插" }, 2);
list.displayList();
list.delete(3);
console.log(list.length);
console.log(list.find(2));