Implementation of Stack Operations in C
There are five basic stack operations:
Operation | Description | Time Complexity | Space Complexity |
---|---|---|---|
Push | Add one element to the top of stack. | O(1) | O(1) |
Pop | Delete one element from the top of stack. | O(1) | O(1) |
Peek | Return the top element. | O(1) | O(1) |
IsFull | Returns true is stack is full. If not, returns false. | O(1) | O(1) |
IsEmpty | Returns true is stack is empty. If not, returns false. | O(1) | O(1) |
1. isFull Implementation
The top pointer will always point to the index that have the current top element. So the stack full condition will be top is greater that or equal to the MAX_SIZE i.e. the size of the array.
Algorithm
- If top == capacity – 1, return true.
- Else, return false
2. isEmpty Implementation
We have set the top = -1 initially when there were no element. This will be true for whenever the stack is empty.
Algorithm
- If top == -1, return true.
- Else, return false
3. Push Implementation
The push operation will be performed at the top of the stack. The top variable points to the current top element, so we need to increment it to insert the new element the top. But before, we need to check whether the given stack is full or not. Pushing an element while the stack is full is called stack overflow.
Algorithm
- If stack is full, print stack overflow and return.
- Else, increment the top and insert the new element at arr[top].
4. Pop Implementation
The pop operation is also performed at the top. But in array, we cannot remove the element directly. So, we just decrement the top pointer effectively removing the current top element. But removing element from the stack that is empty leads to the stack underflow condition.
- If the stack is empty (top == -1), print “stack underflow” and return.
- Otherwise, decrement the top.
5. Peek Implementation
The peek operation returns the top element of the stack without removing it. We can access the top element as arr[top].
Algorithm
- If the stack is empty, print “Stack is Empty!” and return -1.
- Else, return arr[top].
Implementation of Stack Using Array in C
A stack is a linear data structure that follows the Last In First Out (LIFO) principle. This means that the most recently added element is the first one to be removed. In this article, we will learn how to implement a stack using an array in C.