class Node {
constructor(value) {
this.value = value;
this.prev = null;
this.next = null;
}
}
class DoublyLinkedList {
constructor() {
this.head = null;
this.tail = null;
}
isEmpty() {
return this.head === null;
}
push(newNode) {
if (!this.head) {
this.head = newNode;
this.tail = newNode;
} else {
let node = this.tail;
node.next = newNode;
newNode.prev = node;
this.tail = newNode;
}
}
pop() {
if (!this.isEmpty()) {
if (this.head === this.tail) {
const tail = this.tail;
this.head = null;
this.tail = null;
return tail;
} else {
const tail = this.tail;
const nextTail = this.tail.prev;
tail.prev = null;
nextTail.next = null;
this.tail = nextTail;
return tail;
}
}
}
print() {
if (!this.isEmpty()) {
const result = [];
let node = this.head;
while (node) {
result.push(node.value);
node = node.next;
}
console.log(result);
}
}
hasValue(value) {
if (!this.isEmpty()) {
let node = this.head;
while (node) {
if (node.value === value) {
return true;
}
node = node.next;
}
return false;
}
}
getLength() {
return this.length;
}
popIndexOf(index) {
if (index <= this.length) {
let currentIndex = 1;
let node = this.head;
while (currentIndex !== index) {
node = node.next;
currentIndex += 1;
}
const prevNode = node.prev;
if (this.tail === node) {
this.tail = prevNode;
prevNode.next = null;
} else {
const nextNode = node.next;
prevNode.next = nextNode;
nextNode.prev = prevNode;
}
node.prev = null;
node.next = null;
return node;
}
}
}