Here is a reference implementation for a Stack in JavaScript:
StackTry in REPL1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| function Stack() { this.top = null; this.size = 0; } function Node(data) { this.data = data; this.next = null; } Stack.prototype.push = function(data) { const node = new Node(data); node.next = this.top; this.top = node; this.size++; }; Stack.prototype.pop = function() { if (this.top === null) return; const data = this.top.data; this.top = this.top.next; this.size = Math.max(0, this.size - 1); return data; }; Stack.prototype.peek = function() { if (!this.top) return; return this.top.data; }; Stack.prototype.isEmpty = function() { return this.size === 0 && !this.top; };
|
Tests can be found at REPL.it