Stack & Queue

node v8.9.3
version: 2.0.0
endpointsharetweet
// Stack class Stack { constructor() { this.size = 0; this.storage = {}; } push(val) { let size = ++this.size; this.storage[size] = val; } pop() { let size = this.size; let deleted; deleted = this.storage[size]; delete this.storage[size]; this.size--; return deleted; } } const stack = new Stack(); stack.push(5); stack.push(4); stack.push(3); stack.push(2); console.log('STACK', stack.storage); console.log('POP', stack.pop()); // QUEUE class Queue { constructor() { this.oldestIndex = 1; this.newestIndex = 1; this.storage = {}; } enqueue(val) { this.storage[this.newestIndex] = val; this.newestIndex++; } dequeue() { let oldestIndex = this.oldestIndex; let newestIndex = this.newestIndex; let deletedData; if (oldestIndex !== newestIndex) { deletedData = this.storage[oldestIndex]; delete this.storage[oldestIndex]; this.oldestIndex++; return deletedData; } } } const queue = new Queue(); queue.enqueue(1); queue.enqueue(2); queue.enqueue(3); queue.enqueue(4); console.log('DEQUEUE', queue.dequeue()) console.log('DEQUEUE', queue.dequeue())
Loading…

no comments

    sign in to comment