Stack with LinkedList

Run Settings
LanguageJavaScript
Language Version
Run Command
class Node { constructor(value) { this.value = value; this.next = null; } } class Stack { constructor() { this.top = null; this.bottom = null; this.length = 0; } peek() { return this.top; } push(value) { const newNode = new Node(value); newNode.next = this.top; this.top = newNode; if (this.length === 0) { this.bottom = newNode; } this.length++; return this; } pop() { if (this.length <= 1) { this.top = null; this.bottom = null; this.length = Math.max(this.length-1,0); return this; } const secondLast = this.top.next; delete this.top; this.top = secondLast || this.bottom; this.length--; return this; } } const stack = new Stack(); stack.push(10); stack.push(12); stack.push(11); stack.push(14); // stack.pop(); // stack.pop(); // stack.pop(); // stack.pop(); // stack.pop(); // stack.pop(); // stack.pop(); console.log(stack.pop()); console.log(stack.peek())
class Node { constructor(value) { this.value = value; this.next = null; } } class Stack { constructor() { this.top = null; this.bottom = null; this.length = 0; } peek() { return this.top; } push(value) { const newNode = new Node(value); if (this.length === 0) { this.top = newNode; this.bottom = newNode; } else { const holdingPointer = this.top; this.top = newNode; this.top.next = holdingPointer; } this.length++; return this; } pop() { if (!this.top) { return null; } if (this.top === this.bottom) { this.bottom = null; } const holdingPointer = this.top; this.top = this.top.next; this.length--; return holdingPointer; } } const stack = new Stack(); stack.push(10); stack.push(12); stack.push(11); stack.push(14); stack.pop(); // stack.pop(); // stack.pop(); // stack.pop(); // stack.pop(); // stack.pop(); // stack.pop(); console.log(stack.pop());
Editor Settings
Theme
Key bindings
Full width
Lines