Implement a stack from scratch
Problem
Implement a stack (LIFO) with push, pop, peek, isEmpty and size, backed by an array or a linked list. Handle popping from an empty stack.
Example 1
Input: push(1), push(2), pop(), peek() Output: 2, 1
Also asked as: Implement Stack from Scratch
Test cases
Case 1
Input: new Stack() .push(1) .push(2) .pop() .peek() .size() .isEmpty() Expected: [null,null,2,1,1,false]
Case 2
Input: new Stack() .push(5) .pop() .isEmpty() Expected: [null,5,true]
Case 3
Input: new Stack() .isEmpty() .pop() .size() Expected: [true,null,0]
View solutionHide solution1 approach
1. Backed by an array
Time O(1) per opSpace O(n)
push/pop/peek at the array end are O(1); track size explicitly if you avoid `length`.
class Stack { #a = []; push(x) { this.#a.push(x); } pop() { return this.#a.pop(); } peek() { return this.#a[this.#a.length - 1]; } isEmpty() { return this.#a.length === 0; } size() { return this.#a.length; }}