Public
Edited
Apr 21
Insert cell
Insert cell
class ListNode {
constructor(value, next = null, prev = null) {
Object.assign(this, { value, next, prev });
}
}
Insert cell
class Deque {
constructor() {
this.head = this.tail = null;
}
//
// Returns true iff the deque is empty
empty() {
return this.head === null;
}
//
// Removes the first node at the beginning of the deque and returns its value
// Throws an error if empty
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; // estava com apenas um elemento
}
return value;
}
//
// Removes the last node at the end of the deque and returns its value
// Throws an error if empty
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; // estava com apenas um elemento
}
return value;
}
//
// Adds a new node with the given value at the front (head) of the deque
pushFront(value) {
const node = new ListNode(value, this.head, null);
if (this.head) {
this.head.prev = node;
} else {
this.tail = node; // primeiro nó inserido
}
this.head = node;
}
// Adds a new node with the given value at the back (tail) of the deque
pushBack(value) {
const node = new ListNode(value, null, this.tail);
if (this.tail) {
this.tail.next = node;
} else {
this.head = node; // primeiro nó inserido
}
this.tail = node;
}
// Generates all values in the deque from front to back
*all() {
let current = this.head;
while (current) {
yield current.value;
current = current.next;
}
}
// Generates all values in the deque in reverse order (from back to front)
*allReversed() {
let current = this.tail;
while (current) {
yield current.value;
current = current.prev;
}
}
}

Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
{
let d = new Deque();
for (let x of sampleValues) d.pushFront(x);
return [...d.all()];
}
Insert cell
Insert cell
deque = {
let d = new Deque();
for (let x of sampleValues) d.pushBack(x);
return d;
}
Insert cell
[...deque.all()]
Insert cell
Insert cell
{
let d = new Deque();
for (let x of sampleValues) {
if (x % 4 == 2 && !d.empty()) d.popBack();
else if (x % 4 == 3 && !d.empty()) d.popFront();
else if (x % 4 == 0) d.pushFront(x);
else if (x % 4 == 1) d.pushBack(x);
}
return [...d.allReversed()].filter(x => x !== 13);
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more