Algorithm
Stack Implementation (Using Array):
- Initialize an array
stack[]
to store the elements of the stack. - Initialize a variable
top
to-1
to represent the top of the stack. - Define the following operations:
- Push: Add an element to the stack.
- Check if the stack is full. If
top == maxSize - 1
, display an overflow error. - Otherwise, increment
top
and setstack[top] = element
.
- Check if the stack is full. If
- Pop: Remove the top element from the stack.
- Check if the stack is empty. If
top == -1
, display an underflow error. - Otherwise, return
stack[top]
and decrementtop
.
- Check if the stack is empty. If
- Peek: Retrieve the top element without removing it.
- Check if the stack is empty. If
top == -1
, display an error. - Otherwise, return
stack[top]
.
- Check if the stack is empty. If
- IsEmpty: Check if the stack is empty by verifying if
top == -1
. - IsFull: Check if the stack is full by verifying if
top == maxSize - 1
.
- Push: Add an element to the stack.
Example:
Consider a stack with a maximum size of 5. Perform the following operations:
- Push 10, 20, 30
- Pop an element
- Peek the top element
The stack will contain [10, 20] after these operations, and the top element will be 20.