Step 2 of 5
40% CompletePush Operation
Learn how to add elements to a stack
The Push Operation
The push operation adds an element to the top of the stack. It's one of the fundamental operations that defines a stack's behavior.
Think of it like placing a plate on top of a stack of plates. The new plate becomes the top of the stack, and it's the first one you'll remove when you need a plate.
Implementing Push
In our array-based implementation, the push operation is straightforward. We simply add the new element to the end of the array, which represents the top of our stack.
class Stack {constructor() {this.items = [];}// Push: Add an element to the top of the stackpush(element) {// Simply add the element to the end of the arraythis.items.push(element);// Optional: return this for method chainingreturn this;}// Other methods...}
Before Push
The stack is empty
After Push(40)
The stack is empty
How Push Works
Let's break down the push operation step by step:
- Accept an element - The push method takes a parameter, which is the element to be added to the stack.
- Add to the top - In our array implementation, we add the element to the end of the array using the built-in
push
method of JavaScript arrays. - Return the stack instance - Optionally, we return
this
(the stack instance) to allow for method chaining, which can be useful in some scenarios.
Key Points About Push:
- Time Complexity: O(1) - The push operation is constant time, meaning it takes the same amount of time regardless of how many elements are in the stack.
- Stack Growth: In JavaScript, arrays automatically resize, so we don't need to worry about stack overflow. In languages with fixed-size arrays, you would need to check if the stack is full before pushing.
- Method Chaining: Returning
this
allows for method chaining likestack.push(10).push(20).push(30)
.
Push Operation in Action
Here's an example of using the push operation to build a stack:
// Create a new stackconst stack = new Stack();// Push elements onto the stackstack.push(10);stack.push(20);stack.push(30);// Stack now contains [10, 20, 30] with 30 at the top// We can also chain push operationsstack.push(40).push(50);// Stack now contains [10, 20, 30, 40, 50] with 50 at the top
The stack is empty
Check Your Understanding
Next Steps
Now that you understand how to add elements to a stack with the push operation, let's move on to learning how to remove elements with the pop operation.