Problem Statement
Using the provided Stack class, perform push and pop operations to demonstrate how elements are added and removed following the Last In, First Out (LIFO) principle. The Stack class already implements the core stack functionality - you just need to use the push() and pop() methods appropriately.
Example Usage
- Output:
2
(popped)
1
(popped)
null
(stack is empty)
JavaScript Stack - Using Custom Stack Class Methods
Here, we’ll use a Stack
class that we have already defined. This class allows the following operations:
push
- Adds an item to the top of the stack.
pop
- Removes and returns the top item from the stack.
peek
- Returns the top item without removing it.
isEmpty
- Checks if the stack has any items.
size
- Returns the number of items in the stack.
clear
- Removes all items from the stack.
The custom Stack class defined is as follows:
Approach
- Initialize a Stack: Create an instance of the
Stack
class.
- Push Operations: Use the
push
method to add elements to the stack.
- Pop Operations: Use
pop
to remove the top element from the stack and return it.
- Check if Empty: Use
isEmpty
to verify if there are items in the stack before performing operations.
- Handle Empty Stack: If attempting to
pop
from an empty stack, return null
as a safeguard.
Steps
- Create an instance of the
Stack
class.
- Push items onto the stack using
push
.
- Remove items from the stack using
pop
.
- Use
isEmpty
to check the stack’s state before each operation.
- Test with additional
pop
calls to check the handling of empty stacks.
Time & Space Complexity
- Time Complexity:
push
and pop
operations are O(1), as adding/removing from the end of an array is constant time.
- Space Complexity: O(n), where
n
is the number of elements in the stack.
Code Snippet
Dry Run
Given the input sequence:
- push(1): Adds
1
to the stack. Stack state: [1]
- push(2): Adds
2
to the stack. Stack state: [1, 2]
- pop(): Removes
2
from the stack. Output: 2
, Stack state: [1]
- pop(): Removes
1
from the stack. Output: 1
, Stack state: []
- pop(): Stack is empty, so returns
null
. Stack state remains []
.
Complexity Analysis
Custom Defined Stack Methods
- Time Complexity: Push and pop operations are both O(1).
- Space Complexity: O(n), proportional to the number of items in the stack.
Conclusion
This custom Stack
class allows us to simulate a stack with efficient push
and pop
operations. Using this class, we can easily perform LIFO operations with simple method calls. The class handles empty stack cases gracefully by returning null
for pop
operations on an empty stack.