Stack_linked_list

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.value; } push(value) { let node = new Node(value); if (this.length === 0) { this.top = node; this.bottom = node; this.length++; return this; } node.next = this.top; this.top = node; this.length++; return this; } pop() { if (this.length === 0) { return null; } if (this.length === 1) { let val = this.top.value; this.top = null; this.bottom = null; this.length = 0; return val; } let val = this.top.value; let next = this.top.next; this.top = next; this.length--; return val; } isEmpty() { return (this.length === 0); } // print the elements in the stack printList() { const values = []; let node = this.top; while (node !== null) { values.push(node.value); node = node.next; } console.log(values.join(" | ")); } } const myStack = new Stack(); console.log(myStack.isEmpty()); myStack.push(10); myStack.push(20); myStack.push(30); myStack.push(40); console.log(myStack.peek()); myStack.printList(); console.log(myStack.pop()); myStack.printList(); console.log(myStack.isEmpty()); console.log(myStack.length); console.log(myStack);
Editor Settings
Theme
Key bindings
Full width
Lines