Implement a Stack in C Programming (original) (raw)
Last Updated : 13 Nov, 2024
Stack is the linear data structure that follows the Last in, First Out(LIFO) principle of data insertion and deletion. It means that the element that is inserted last will be the first one to be removed and the element that is inserted first will be removed at last. Think of it as the stack of plates stacked on top of one another where we can only add or remove the top plate.
Stacks are widely used in programming for tasks like expression evaluation, function call management, and backtracking algorithms. In this article, we will learn how to implement a stack in the C programming language. We will also look at some of its basic operations along with their time and space complexity analysis.
Implementation of a Stack in C
In C, we can implement a stack using an array or a linked list. In this article, we will use the array data structure to store the stack elements and use a pointer to keep track of the topmost element of the stack. The stack will offer some basic operations like push, pop, peek, isEmpty, and isFull to the users.
Representation of Stack in C
The stack can be represented as a structure that contains a fixed-size array in C which stores the data of the stack and an index pointer which is used to track the top element of the stack.
struct stack {
type arr[MAX_SIZE];
int top;
}
We can use a utility function initialize the stack array along with the top pointer. The initial value of the top should be -1 representing that there are currently no elements in the stack.
Max size of the stack can be defined as per our requirements.
Basic Stack Operations in C
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.
1. isFull Function
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.
2. isEmpty Function
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.
3. Push Function
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
Following is the algorithm for the push operation:
- Check whether if the stack is full.
- If stack is full then display the overflow message.
- If stack is not full then increment the top pointer.
- Add the new element to position pointed to by the top pointer.
4. Pop Function
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
Following is the algorithm for the pop operation:
- 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.
5. top Function
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
Following is the algorithm for top operation on the stack:
- Check whether the stack is empty.
- If it is empty, return -1.
- Else return, stack.data[top] element.
C Program To Implement a Stack
The following program demonstrates how we can implement a Stack in C:
C `
// C Program to demonstrate how to Implement a Stack #include <stdio.h> #include <stdbool.h>
// Define the maximim capacity of the stack #define MAX_SIZE 100
// Define a structure for the stack
typedef struct {
// Array to store stack elements
int arr[MAX_SIZE];
// Index of the top element in the stack
int top;
} Stack;
// Function to initialize the stack
void initialize(Stack *stack) {
// Set top index to -1 to indicate an empty stack
stack->top = -1;
}
// Function to check if the stack is empty
bool isEmpty(Stack *stack) {
// If top is -1, the stack is empty
return stack->top == -1;
}
// Function to check if the stack is full
bool isFull(Stack *stack) {
// If top is MAX_SIZE - 1, the stack is full
return stack->top == MAX_SIZE - 1;
}
// Function to push an element onto the stack void push(Stack *stack, int value) { // Check for stack overflow if (isFull(stack)) { printf("Stack Overflow\n"); return; } // Increment top and add the value to the top of the stack stack->arr[++stack->top] = value; printf("Pushed %d onto the stack\n", value); }
// Function to pop an element from the stack int pop(Stack *stack) { // Check for stack underflow if (isEmpty(stack)) { printf("Stack Underflow\n"); return -1; } // Return the top element int popped = stack->arr[stack->top]; // decrement top pointer stack->top--; printf("Popped %d from the stack\n", popped); // return the popped element return popped; }
// Function to peek the top element of the stack int peek(Stack *stack) { // Check if the stack is empty if (isEmpty(stack)) { printf("Stack is empty\n"); return -1; } // Return the top element without removing it return stack->arr[stack->top]; }
int main() { Stack stack; // Initialize the stack initialize(&stack);
// Push elements onto the stack and print the stack after each push
push(&stack, 3);
printf("Top element: %d\n", peek(&stack));
push(&stack, 5);
printf("Top element: %d\n", peek(&stack));
push(&stack, 2);
printf("Top element: %d\n", peek(&stack));
push(&stack, 8);
printf("Top element: %d\n", peek(&stack));
// Pop elements from the stack and print the stack after each pop
while (!isEmpty(&stack)) {
printf("Top element: %d\n", peek(&stack));
printf("Popped element: %d\n", pop(&stack));
}
return 0;
}
`
**Output
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
Popped element: 8
Top element: 2
Popped 2 from the stack
Popped element: 2
Top element: 5
Popped 5 from the stack
Popped element: 5
Top element: 3
Popped 3 from the stack
Popped element: 3
Applications of Stack in C
Stack is widely used for Following are some common applications of Stack:
- Stacks are commonly used to evaluate postfix expressions. It is also used in infix to postfix conversion.
- It is used in recursion where a different stack is allocated for every recursive call.
- It is used in browsers to provide the backward and forward functionality.
- It is also used in text editor, image editors to provide the undo and redo funtionality.
- It is used in various algorithms in computer science.