Operations on Stack
Key operations performed on a stack data structure
Operations
Push
Add an element to the top of the stack.
-
Before adding an element to the stack, we check if the stack is full.
-
If the stack is full (
top==capacity-1
), we get a Stack Overflow and cannot add any more elements. -
If the stack isn't full, we increase the top by 1 (
top = top + 1
) and insert the new element at that position. -
We can keep adding elements until the stack reaches its capacity.
Push
Remove the top element from the stack.
-
Before removing an element from the stack, we check if it’s empty.
-
If the stack is empty (
top==-1
), we can't remove anything, which is called Stack Underflow. -
If the stack has elements, we get the value at the top, move the top down by
1
, and return the value we retrieved.
Peek/Top
View the top element without removing it.
- Return the top element of the Stack.
IsEmpty
Check if the stack is empty.
-
Check for the value of top in stack.
-
If (
top == -1
), then the stack is empty so return true . -
Else, the stack is not empty so return false .
IsFull
Check if the stack has reached its maximum capacity (in fixed-size stacks).
-
Check the value of top in the stack.
-
If (
top == capacity - 1
), the stack is full, so return true. -
Else, the stack isn't full, so return false.