![]() |
VOOZH | about |
A stack is a linear data structure that follows the Last In, First Out (LIFO) principle, meaning the last element added is the first one to be removed.
top pointer, which is initialized to -1 to indicate an empty stack.Following are some basic operations in the stack that make it easy to manipulate the stack data structure:
Operation | Description | Time Complexity | Space Complexity |
|---|---|---|---|
Push | Inserts an element at the top of the stack. | O(1) | O(1) |
Pop | Removes the top most element of the stack. | O(1) | O(1) |
Peek | Returns the topmost element of the stack. | O(1) | O(1) |
IsFull | Returns true is the stack is full otherwise returns false. | O(1) | O(1) |
IsEmpty | Returns true is the stack is empty otherwise returns false. | O(1) | O(1) |
As we can see, the stack offers O(1) time complexity for all the operation but with a catch that we can only perform these operation to the topmost element. So, we need to consider our requirements to take advantage of stack data structure.
Let's see how to implement these basic operations for our stack in C.
Pushed 3 onto the stack Top element: 3 Pushed 5 onto the stack Top element: 5 Pushed 2 onto the stack Top element: 2 Pushed 8 onto the stack Top element: 8 Top element: 8 Popped 8 from the stack Poppe...
The isFull() function provides the information about whether the stack have some space left or it is completely full. We know that the max capacity of the stack is MAX_SIZE elements. So, the max value of top can be MAX_SIZE - 1.
Algorithm of Stack isFull:
- If top >= MAX_SIZE - 1, return true.
- Else return false.
The isEmpty function will check whether the stack is empty or not. We know that when the stack is empty, the top is equal to -1.
Algorithm of Stack isEmpty:
- If the top pointer==-1 return true
- Else return false.
The push function will add (or push) an element to the stack. The edge case here will be when we try to add a new element when the stack is already full. It is called stack overflow and we have to check for it before inserted new element.
Algorithm of Stack Push:
The pop function will remove an element from the stack. One case that can occur here is when we try to remove the top using pop() function when the stack is already empty. Such condition is called stack underflow and can be easily checked.
Algorithm of Stack Pop:
- Check whether if stack is empty.
- If stack is empty then display the underflow message.
- If stack is not empty then remove the element at top position
- Decrement the top pointer of the stack.
The peek function will return the topmost element of the stack in constant time. If the stack is empty it returns -1.
Algorithm for Stack Top Function
- Check whether the stack is empty.
- If it is empty, return -1.
- Else return, stack.data[top] element.