View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Stack in C

Updated on 05/02/20257,309 Views

A stack is a data structure that follows the Last In, First Out (LIFO) principle. It allows you to add and remove elements from the top. For example, when you place plates on a stack, you remove the top plate first. In programming, stack operations allow you to add and remove elements from the top. 

Implementing stack operations in C can be tricky, especially when handling dynamic memory and pointers. 

This tutorial will guide you through implementing a stack in C program, along with essential stack operations. Let’s dive into the details!

Boost your C programming skills with our Software Development courses — take the next step in your learning journey! 

Representing a Stack in C

In C, a stack can be represented using either an array or a linked list. An array-based implementation is straightforward and useful for stacks of fixed size, while a linked list implementation is dynamic and allows for a flexible size. 

In this representation, the stack is implemented as an array, with the top of the stack being managed by an index variable. 

Stack in C

Here’s the basic structure: 

#define MAX 100  // Maximum stack size
int stack[MAX];  // Stack array
int top = -1;    // Initialize top of stack as -1
Alternatively, you can use a linked list to represent a stack. In this case, each stack element is stored in a node, with each node pointing to the next one. 
struct Node {
    int data;
    struct Node* next;
};

struct Node* top = NULL;

Both approaches are effective, but using a linked list is more flexible as it avoids the need to predefine a size.

Also Read: What are Data Structures in C & How to Use Them?

With the stack structure in place, let’s now explore the key operations that power stack functionality. 

Stack Operations in C

Here’s a quick look at the basic operations performed on a stack:

Operation

Description

Time Complexity

Space Complexity

push()

Inserts an element at the top of the stack.

O(1)

O(1)

pop()

Removes the top element from the stack.

O(1)

O(1)

top()

Returns the top element without removing it.

O(1)

O(1)

isEmpty()

Checks if the stack is empty.

O(1)

O(1)

isFull()

Check if the stack is full.

O(1)

O(1)

push()

The push() operation adds an element to the top of the stack. It first creates a new node and then sets the new node’s pointer to the current top. The top pointer is updated to the new node, effectively making it the new top of the stack.

Algorithm for push():

  1. Create a new node.
  2. Set the node’s data to the value to be added.
  3. Link the node to the current top node.
  4. Update the top pointer to point to the new node. 

pusp operation in stack

pop()

The pop() operation removes the top element from the stack. It first checks if the stack is empty. If not, the top element is removed, and the top pointer is updated to the next node in the stack.

Algorithm for pop():

  1. Check if the stack is empty (top == NULL).
  2. If empty, return an error message or a specific value (like -1).
  3. Otherwise, temporarily store the top node.
  4. Set the top pointer to the next node in the stack.
  5. Free the memory of the old top node. 

pop operation in stack

top()

The top() operation retrieves the top element without removing it. It simply returns the value of the top element without modifying the stack.

Algorithm for top():

  1. Check if the stack is empty (top == NULL).
  2. If empty, return an error message or a specific value.
  3. Otherwise, return the value of the top node.

top peep operation in stack

isEmpty()

The isEmpty() operation checks if the stack is empty. It returns true if the stack is empty (i.e., the top pointer is NULL), and false otherwise.

Algorithm for isEmpty():

  1. Check if the top pointer is NULL.
  2. If NULL, return true (stack is empty).
  3. Otherwise, return false.

isempty operation in stack

isFull()

The isFull() operation checks if the stack is full. This operation isn't always necessary for a dynamic stack (implemented with a linked list) because the stack can grow as needed. For a static stack (e.g., using an array), it checks if the stack has reached its maximum capacity.

Algorithm for isFull():

  1. For dynamic stacks, always return false as the stack can grow.
  2. For static stacks, check if the size has reached the maximum limit.
  3. Return true if the stack is full; otherwise, return false.

ispop operation in stack

Also Read: Types of Operators in C: Roles, Usage & Best Practices 2025

On that note, let's look at the types of stacks and their specific applications.

Types of Stacks in C

In C programming, stacks can be classified into different types based on their implementation. The two main types of stacks are Static Stacks and Dynamic Stacks

Understanding these will help you choose the right one for your application, especially when dealing with stack operations in C.

1. Static Stack

A static stack is implemented using arrays. The stack size is predefined, meaning it has a fixed size at the time of creation. This makes the static stack simple to implement and efficient for small applications where the size of the stack is predictable. 

However, one limitation is that the size cannot be changed dynamically.

Example: 

int top = -1;    #define MAX 100  // Set stack size
int stack[MAX];  // Array for stack
// Initialize top
  • Pros: Simple to implement, fast for small fixed-size stacks.
  • Cons: Limited size, memory is wasted if the stack size is not fully utilized.

2. Dynamic Stack

A dynamic stack is implemented using linked lists. Unlike the static stack, the size of the stack is not predefined. The stack grows and shrinks dynamically as elements are added or removed, making it more flexible than a static stack. 

It avoids memory wastage since it only uses memory as needed.

Example: 

struct Node {
    int data;
    struct Node* next;
};
struct Node* top = NULL;
  • Pros: Flexible size, avoids memory wastage, ideal for larger or unpredictable data.
  • Cons: More complex to implement, slower compared to static stacks due to pointer manipulation.

Here’s the list of a few other types of stacks:

3. Circular Stack

A circular stack wraps the end of the stack to the beginning, making better use of memory, especially in applications with fixed memory limits. Ideal for cases where stack overflow could occur in a linear stack, as it reuses the memory space.

Example: 

struct Node {
    int data;
    struct Node* next;
};
  • Pros: Efficient memory use, no wasted space, reusable space, ideal for buffer-like use cases.
  • Cons: More complex implementation, can lead to confusion if not properly managed. 

4. Double-Ended Stack (Deque)

A double-ended stack (deque) allows inserting and removing elements from both ends, making it a versatile data structure. It's commonly used when you need efficient access to both ends of the stack.

Example: 

struct Node {
    int data;
    struct Node* next;
    struct Node* prev;
};
  • Pros: Fast insertion/removal from both ends, useful for scheduling or multi-threading tasks.
  • Cons: More memory overhead due to extra pointers, complex to implement and manage. 

5. Multi-stack Implementation

A multi-stack implementation uses one array or linked list to manage multiple stacks. This method is useful in systems where different tasks need isolated memory spaces, such as in function calls or memory management systems.

Example: 

int stack[MAX_SIZE];
int top[NUM_STACKS];
  • Pros: Efficient memory use when managing multiple tasks, allows multiple independent stacks in one structure.
  • Cons: Complexity increases when resizing or managing individual stacks, harder to implement, especially when resizing stacks dynamically. 

6. Persistent Stack (Undo Stack)

A persistent stack preserves the history of its operations, enabling users to access previous states. This is perfect for applications like text editors, where users can undo actions and revert to previous versions of data.

Example: 

struct Node {
    char action[100];
    struct Node* next;
};
  • Pros: Allows users to revert to previous states (ideal for undo operations) and maintains a history of actions for recovery.
  • Cons: Consumes more memory due to stored history, potentially slower performance due to maintaining previous states.

Why Choose the Right Stack?

The type of stack you choose affects your program's performance, memory usage, and complexity. 

For example, a static stack is faster but has a fixed size, whereas a dynamic stack offers flexibility but may incur extra memory overhead. A circular stack can be more efficient when memory is reused, and a double-ended stack can optimize tasks that require access from both ends.

Understanding the types of stacks and their use cases can help you make better decisions and build more optimized solutions when performing stack operations in C. 

Implementation of Stack: Browser History (Undo Functionality)

A real-life example of a stack is the browser history. When you visit websites, your browser stores the pages in a stack. The most recent page is always on top. If you press the "Back" button, the top page is popped off the stack, and the browser takes you to the previous page.

For this example, we will implement a simple stack that mimics this functionality with basic stack operations like push(), pop(), top(), isEmpty(), and isFull().

Let’s look at the algorithm: 

  1. Initialize an empty stack: Create a stack that holds the browser pages as strings.
  2. Push Operation: Add a new page to the stack whenever you visit a new website.
  3. Pop Operation: Remove the top page when you press the back button to go to the previous website.
  4. Top Operation: Peek at the current top of the stack (current webpage).
  5. isEmpty: Check if there are no pages in the stack (empty history).
  6. isFull: This operation won't be used here since we are using dynamic memory allocation.

Let’s see how the code works out:  

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Define a node structure for the stack
struct Node {
    char url[100];     // Holds the website address
    struct Node* next; // Points to the next node in the stack
};
// Define the top of the stack (initially NULL)
struct Node* top = NULL;
// Push operation to insert a page (URL) at the top of the stack
void push(char url[]) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); // Allocate memory for a new node
    if (newNode == NULL) {
        printf("Memory overflow\n");
        return;
    }
    strcpy(newNode->url, url);  // Copy the URL into the new node's data field
    newNode->next = top;        // Link the new node to the current top node
    top = newNode;              // Move the top pointer to the new node
    printf("Visited: %s\n", url);  // Print the visited page URL
}
// Pop operation to remove the top page from the stack (back functionality)
void pop() {
    if (top == NULL) {  // Check if the stack is empty (no pages to go back to)
        printf("No history to go back\n");
        return;
    }
    struct Node* temp = top;  // Temporarily store the top node
    printf("Going back to: %s\n", temp->url);  // Print the page we are going back to
    top = top->next;  // Move the top pointer to the next node
    free(temp);       // Free the memory of the old top node
}
// Top operation to view the current page (without popping it)
void topPage() {
    if (top == NULL) {
        printf("No page in history\n");
        return;
    }
    printf("Currently on: %s\n", top->url);  // Print the current top page URL
}
// Check if the stack is empty
int isEmpty() {
    return top == NULL;
}
// Main function to simulate stack operations (browser history)
int main() {
    push("www.google.com");  // Visit Google
    push("www.youtube.com"); // Visit YouTube
    push("www.stackoverflow.com"); // Visit StackOverflow
    topPage();  // Check the current page
    pop();  // Go back to previous page
    pop();  // Go back to previous page
    topPage();  // Check the current page after going back
    return 0;
}

Output: 

Currently on: Visited: www.google.com
Visited: www.youtube.com
Visited: www.stackoverflow.com
Currently on: www.stackoverflow.com
Going back to: www.stackoverflow.com
Going back to: www.youtube.com
www.google.com

Explanation:

  1. Push Operation (Visiting a Website):
    • The URL is pushed onto the stack every time a user visits a page. The top pointer is updated to point to the most recent page.
  2. Pop Operation (Going Back):
    • When the "Back" button is pressed, the top URL is removed from the stack. The top pointer then moves to the previous page in history, effectively going back in the browser.
  3. Top Operation (Current Page):
    • This operation allows us to view the page that was visited most recently (the one at the top of the stack).
  4. isEmpty Operation (Checking if Stack is Empty):
    • This checks whether there is any page in history. If no pages are left, it prints "No history to go back."

In this example, we simulate the browser's "Back" functionality using stack operations in C. The stack holds a history of pages, and you can easily go back through the pages as needed using the pop() operation.

How Well Do You Know Stack in C? 10 MCQs

This quiz will help you test your understanding of stacks in C programming. See if you're ready to dive deeper into this fundamental data structure!

1. What is the main characteristic of a stack in C?

A) First In, First Out (FIFO)

B) Last In, First Out (LIFO)

C) No order

D) Random access

2. Which of the following is the main operation used to add an element to a stack in C?

A) pop()

B) push()

C) peek()

D) remove()

3. What is the default value of the stack pointer if no elements are pushed onto the stack?

A) NULL

B) 0

C) -1

D) Undefined

4. What happens if you attempt to pop an element from an empty stack?

A) Stack overflow

B) Stack underflow

C) No operation

D) Program crashes

5. Which of the following is NOT a method to implement a stack in C?

A) Using arrays

B) Using linked lists

C) Using hash tables

D) Using pointers

6. What is the output of the following C code when running a stack implemented using arrays?

#include <stdio.h>
#define MAX 3
int stack[MAX];
int top = -1;
void push(int val) {
if (top < MAX - 1) {
stack[++top] = val;
}
}
int main() {
push(10);
push(20);
printf("%d\n", stack[top]);
return 0;
}

A) 10

B) 20

C) 30

D) Error

7. What is the time complexity for the push and pop operations in a stack using an array?

A) O(n)

B) O(log n)

C) O(1)

D) O(n^2)

8. What is the role of the "top" pointer in a stack implemented using a linked list?

A) Points to the bottom element of the stack

B) Points to the most recent element pushed onto the stack

C) Tracks the number of elements in the stack

D) Marks the end of the stack

9. How can a stack be used in recursive algorithms?

A) It stores local variables during recursion

B) It helps with function call management

C) It tracks variables to be printed

D) It does not play a role in recursion

10. What is the key disadvantage of using a stack with a fixed size in C?

A) It wastes memory

B) It causes stack overflow when the size limit is exceeded

C) It has slower push/pop operations

D) It limits the number of elements that can be popped

Understanding stack in C is just the beginning—keep building your C programming skills with expert-led courses and hands-on learning.

How Can upGrad Help You Master Stack in C?

upGrad’s courses offer a comprehensive, hands-on approach to mastering C programming, including concepts like stacks, recursion, and data structures. Whether you’re learning how stacks operate or optimizing your stack-based algorithms, upGrad’s expert-led courses will guide you step-by-step through key C programming concepts.

Through our interactive courses, you'll gain practical experience working with stacks, from implementing basic operations to tackling more advanced applications in system-level programming and competitive coding.

Check out upGrad’s programs to advance your knowledge:

You can also get personalized career counseling with upGrad to guide your career path, or visit your nearest upGrad center and start hands-on training today! 

Similar Reads:

Explore C Tutorials: From Beginner Concepts to Advanced Techniques
Array in C: Introduction, Declaration, Initialisation and More
Exploring Array of Pointers in C: A Beginner's Guide
What is C Function Call Stack: A Complete Tutorial
Binary Search in C
Constant Pointer in C: The Fundamentals and Best Practices
Find Out About Data Structures in C and How to Use Them?

FAQs

1. What is the main advantage of using a stack in C program over other data structures?

A. A stack in C program is ideal for LIFO operations, providing efficient access to the most recent element, making it perfect for use cases like undo functionality or recursion.

2. How do stack operations in C compare in terms of efficiency?

A. Stack operations in C, like push and pop, operate in constant time O(1), making them very efficient for managing data with the LIFO structure.

3. Can stack operations in C be implemented without dynamic memory allocation?

A. Yes, stack operations in C can be implemented statically by using arrays, but dynamic memory allocation (linked list) allows for more flexible and scalable stacks.

4. What are some real-life scenarios where stack operations in C are used?

A. Common real-life uses of stack operations in C include managing browser history, implementing undo features in text editors, and handling recursive function calls.

5. How does memory management work with stack operations in C?

A. In dynamic stack implementations, memory is allocated dynamically for each node, ensuring that the stack can grow and shrink as needed, reducing memory wastage.

6. What happens if we try to pop from an empty stack in C?

A. Trying to pop from an empty stack in C program will result in a stack underflow error, which should be handled with a condition check to ensure the stack isn't empty.

7. What is the difference between stack overflow and stack underflow in C?

A. Stack overflow occurs when trying to push to a full stack, while stack underflow occurs when trying to pop from an empty stack.

8. What are the limitations of using an array to implement a stack in C?

A. Using an array to implement a stack in C program limits the stack size, requiring predefined memory allocation, which may lead to memory wastage or overflow.

9. How does the top() operation in stack operations in C work?

A. The top() operation allows you to view the current element at the top of the stack without removing it, providing a peek into the most recent data added.

10. Can stack operations in C be implemented recursively?

A. Yes, stack operations in C can be implemented recursively by using function calls, although managing stack overflow becomes crucial in recursive implementations.

11. Why is it important to check for stack overflow in stack operations in C?

A. Checking for stack overflow is crucial to prevent memory corruption, ensuring that data is not overwritten or causing crashes when the stack exceeds its capacity.

image

Take a Free C Programming Quiz

Answer quick questions and assess your C programming knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Start Learning For Free

Explore Our Free Software Tutorials and Elevate your Career.

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.