Problem Link - Peek, isEmpty, isFull
Problem Statement:
The peek
, isEmpty
, and isFull
are some other functions used in stacks.
-
peek - This function allows you to look at the element at the top of the stack. It’s a way to inspect the next item that would be removed if a pop operation were to be performed.
- For a stack: Peek would return the last item added (since stacks follow Last In, First Out order).
-
isEmpty - This function checks whether a data structure (like a stack, queue, list, etc.) contains any elements or not.
-
If the data structure contains no elements,
isEmpty
returns true. -
If there is at least one element in the data structure,
isEmpty
returns false.
-
-
isFull - This function is typically relevant for a fixed size stack. It allows you to determine if the data structure has reached its maximum capacity.
Approach:
The key idea is to introduce helper functions that allow for better interaction with the stack, such as viewing the top element without removing it, checking if the stack is empty
, and determining if the stack is full.
-
peek Operation:
- If the stack is not empty (
top >= 0
), we return and display the value at thetop
of the stack. - If the stack is empty (
top == -1
), we print an error message indicating that no elements can be “peeked” at.
- If the stack is not empty (
-
isEmpty Operation:
- This function simply checks if the value of
top
is-1
. If it is, the stack is empty, and it returns1
(true). Otherwise, it returns0
(false), meaning the stack has elements.
- This function simply checks if the value of
-
isFull Operation:
- This function checks if the stack is full by comparing
top
toMAX_SIZE
. Iftop
has reachedMAX_SIZE
, the stack is full and returns1
(true), otherwise it returns0
(false).
- This function checks if the stack is full by comparing
Time Complexity:
- peek, isEmpty, and isFull all have a time complexity of O(1) since they perform a constant amount of work by checking the value of
top
.
Space Complexity:
- The space complexity remains O(MAX_SIZE), which is the space used by the array
a
to store the elements of the stack. No additional space is required for these operations.