Mental Model
A stack is like a pile where you add new items only on top. Push means putting a new item on the top of this pile.
Analogy: Imagine a stack of plates. When you add a new plate, you always put it on the top of the stack.
Top -> null
Top -> null
5 -> null
5 -> null
Top -> 5 -> null
Top -> 5 -> null
class Node { value: number; next: Node | null; constructor(value: number) { this.value = value; this.next = null; } } class Stack { top: Node | null; constructor() { this.top = null; } push(value: number): void { const newNode = new Node(value); // create new node newNode.next = this.top; // link new node to current top this.top = newNode; // update top to new node } print(): void { let curr = this.top; let result = ''; while (curr !== null) { result += curr.value + ' -> '; curr = curr.next; } result += 'null'; console.log(result); } } // Driver code const stack = new Stack(); stack.push(5); stack.print();
const newNode = new Node(value); // create new nodenewNode.next = this.top; // link new node to current topthis.top = newNode; // update top to new nodethis.top = newNode; // update top to new node
push operation do in a stack data structure?5 into a stack array named stack?push() to add elements at the end (top for stack).push on the array with the element as argument: stack.push(5);const stack: number[] = []; stack.push(10); stack.push(20); stack.push(30);
push(10), stack = [10]. After push(20), stack = [10, 20]. After push(30), stack = [10, 20, 30].let stack: number[] = [1, 2, 3]; stack.push 4;
stack.push(4);. The code uses stack.push 4; which is invalid.[4, 5, 6] onto the stack in one operation while preserving their order (4 at bottom, 6 at top)?stack.push(...[4, 5, 6]) spreads the array elements as separate arguments, pushing 4, then 5, then 6 in order.stack.push([4, 5, 6]) pushes the entire array as one element, not separate elements.unshift adds elements at the start, not top of stack.Pass the test and this pattern moves unknown