Implement a Stack in C Programming
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.
Related Articles:
Similar Reads
Stack implementation in C++
Stack is the fundamental data structures used in the computer science to the store collections of the objects. It can operates on the Last In, First Out (LIFO) principle where the most recently added the object is the first one to be removed. It can makes the stacks highly useful in the situations w
4 min read
Perl | Implementing a Stack
Stack in Perl is a linear data structure that follows the LIFO (Last In First Out) or FILO (First In Last Out) order. In simpler terms, a stack is an array in which insertion and deletion takes place at only one end called the top of the stack. Pushing is the process of insertion of elements into a
4 min read
C++ Program to Implement Stack using array
Stack is the fundamental data structure that can operates the under the Last In, First Out (LIFO) principle. This means that the last element added to the stack is the first one to be removed. Implementing the stack using the array is one of the most straightforward methods in the terms of the both
4 min read
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. Implementation of Stack Using Arrays in CIn the array-b
5 min read
Java Program to Implement Stack Data Structure
Stack is the fundamental Data Structure that can follow the Last In, First Out(LIFO) principle. It can work that the last element added to the stack will be the first one to be removed. It can operate like a stack of plates: We can only add or remove the topmost plate at any given time. The simplici
5 min read
LMNs-C Programming
C programming is a powerful and widely-used programming language that forms the backbone of many modern technologies. Known for its simplicity and efficiency, it is the foundation for learning advanced programming concepts. C programming is a powerful and widely-used programming language that forms
7 min read
C++ Program to Implement Queue using Array
A queue is a linear data structure that consists of elements arranged in a sequential order where one end is used to add elements, and another for removing them which results in the FIFO (First-In First-Out) order of operations. In this article, we will learn how to write a program to implement queu
8 min read
Maximum Stack Size for C/C++ Program
Stack size is a crucial aspect of C/C++ programming that determines the amount of memory available for storing function call frames and local variables. In this article, we will discuss the importance of stack size, how it is determined, how to check and increase it, and best practices for managing
4 min read
C Program to Implement Circular Queue
A circular queue is a linear data structure that follows the FIFO (First In, First Out) principle but connects the last position back to the first, forming a circle. In this article, we will learn how to implement circular queue in C programming language. What is a Circular Queue in C?In a circular
5 min read
C Programming Interview Questions (2025)
At Bell Labs, Dennis Ritchie developed the C programming language between 1971 and 1973. C is a mid-level structured-oriented programming and general-purpose programming. It is one of the oldest and most popular programming languages. There are many applications in which C programming language is us
15+ min read