Problem Statement
Using the provided Stack class, perform peek operations to check the top element of the stack without removing it. The Stack class already implements the peek() method - you just need to use it appropriately to view the top element while maintaining the stack's contents.
Example Usage
Additional Examples:
-
Input:
- Output:
null
(stack is empty after pop)
JavaScript Stack - Using Custom Stack peek
Method
We will use the following Stack
class, which allows us to perform operations like push
, pop
, peek
, isEmpty
, size
, and clear
.
Approach
- Push Elements: Add elements to the stack using
push
.
- Peek at the Top: Use the
peek
method to get the top element without removing it.
- Handle Empty Stack: The
peek
method will return null
if the stack is empty.
Steps
- Create an instance of the
Stack
class.
- Use
push
to add elements to the stack.
- Use
peek
to view the top element without modifying the stack.
- Test cases include an empty stack check to ensure that
peek
returns null
when no items are present.
Time & Space Complexity
- Time Complexity:
push
, pop
, and peek
operations are O(1) because they operate at the end of the array.
- Space Complexity: O(n), where
n
is the number of elements in the stack.
Code Snippet
Dry Run
For the input sequence:
- push(3): Adds
3
to the stack. Stack state: [3]
- peek(): Returns
3
, the top of the stack. Stack state remains [3]
- push(5): Adds
5
to the stack. Stack state: [3, 5]
- push(10): Adds
10
to the stack. Stack state: [3, 5, 10]
- peek(): Returns
10
, the current top of the stack. Stack state remains [3, 5, 10]
- pop(): Removes
10
from the stack. Stack state: [3, 5]
- peek(): Returns
5
, the new top of the stack.
- clear(): Empties the stack. Stack state:
[]
- peek(): Stack is empty, so returns
null
.
Complexity Analysis
Custom Defined Stack Methods
- Time Complexity:
push
, pop
, and peek
are O(1).
- Space Complexity: O(n) for storage, where
n
is the number of items.
Conclusion
The peek
method in our custom Stack
class allows us to check the top element without removing it. This operation provides a useful way to inspect the stack’s top item, while the stack's overall simplicity enables efficient LIFO (Last In, First Out) operations.