class Deque {
constructor() {
this.head = this.tail = null;
}
empty() {
return this.head === null;
}
popFront() {
if (this.empty()) throw new Error("Deque is empty");
const value = this.head.value;
this.head = this.head.next;
if (this.head) {
this.head.prev = null;
} else {
this.tail = null;
}
return value;
}
popBack() {
if (this.empty()) throw new Error("Deque is empty");
const value = this.tail.value;
this.tail = this.tail.prev;
if (this.tail) {
this.tail.next = null;
} else {
this.head = null;
}
return value;
}
pushFront(value) {
const node = new ListNode(value, this.head, null);
if (this.head) {
this.head.prev = node;
} else {
this.tail = node;
}
this.head = node;
}
pushBack(value) {
const node = new ListNode(value, null, this.tail);
if (this.tail) {
this.tail.next = node;
} else {
this.head = node;
}
this.tail = node;
}
*all() {
let current = this.head;
while (current) {
yield current.value;
current = current.next;
}
}
*allReversed() {
let current = this.tail;
while (current) {
yield current.value;
current = current.prev;
}
}
}