For working professionals
For fresh graduates
More
5. Array in C
13. Boolean in C
18. Operators in C
33. Comments in C
38. Constants in C
41. Data Types in C
49. Double In C
58. For Loop in C
60. Functions in C
70. Identifiers in C
81. Linked list in C
83. Macros in C
86. Nested Loop in C
97. Pseudo-Code In C
100. Recursion in C
103. Square Root in C
104. Stack in C
106. Static function in C
107. Stdio.h in C
108. Storage Classes in C
109. strcat() in C
110. Strcmp in C
111. Strcpy in C
114. String Length in C
115. String Pointer in C
116. strlen() in C
117. Structures in C
119. Switch Case in C
120. C Ternary Operator
121. Tokens in C
125. Type Casting in C
126. Types of Error in C
127. Unary Operator in C
128. Use of C Language
How do you build a stack in C when you don’t want to fix its size in advance?
The answer is simple—use a stack using linked list in C.
A stack using linked list in C removes the limitation of fixed memory size that comes with arrays. It lets you perform standard stack operations like push, pop, and peek dynamically, using pointers and nodes. This structure is widely used in memory-efficient programs, recursion management, and backtracking algorithms.
In this tutorial, you’ll learn how to create and manage a stack using linked list in C. We’ll walk through each operation—explaining the logic, structure, and code behind it. You’ll also understand how memory allocation and pointer manipulation help make the stack flexible and scalable.
By the end, you'll be able to implement your own stack using linked list from scratch. Want to master data structures in depth? Check out our Software Engineering Courses where you build real projects using core C concepts like these.
A stack is commonly used in applications such as text editors' undo functionality, web browser history, and expression evaluation. This section will focus on a practical example of implementing undo functionality using a stack.
Imagine you are developing a text editor that supports the undo feature. The action is stored in a stack every time the user types something. When the user presses undo, the most recent action is popped from the stack, allowing the editor to revert to the previous state.
Pressing "undo" after the stack is empty should be handled gracefully by displaying a message or preventing further undo actions.
Feeling confident with C programming? It's the perfect time to broaden your technical expertise. Consider exploring these carefully selected courses:
Let’s break down the steps involved:
1. Initialize the Stack:
2. Push Operation (Add Action to Stack):
3. Pop Operation (Undo Action):
4. Handle Empty Stack:
5. Testing:
Let’s walk through this undo functionality implementation using the stack using linked list algorithm.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Define a node structure for the stack
struct Node {
char data[100]; // Store text entered by the user (up to 100 characters)
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 an element (text) at the top of the stack
void push(char text[]) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); // Allocate memory for the new node
if (newNode == NULL) { // Check for memory allocation failure
printf("Memory overflow\n");
return;
}
strcpy(newNode->data, text); // Copy the text 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("Text added: %s\n", text); // Print the added text
}
// Pop operation to remove the top element (undo action)
void pop() {
if (top == NULL) { // Check if the stack is empty (no actions to undo)
printf("No actions to undo\n");
return;
}
struct Node* temp = top; // Temporarily store the top node
printf("Undo: %s\n", temp->data); // Print the action to be undone
top = top->next; // Move the top pointer to the next node
free(temp); // Free the memory of the old top node
}
int main() {
push("Typed: Hello, World!"); // Simulate typing text
push("Typed: How are you?"); // Simulate typing more text
push("Typed: Goodbye!"); // Another text input
pop(); // Undo the last action (Goodbye!)
pop(); // Undo the second last action (How are you?)
pop(); // Undo the first action (Hello, World!)
return 0;
}
Output:
Text added: Typed: Hello, World!
Text added: Typed: How are you?
Text added: Typed: Goodbye!
Undo: Typed: Goodbye!
Undo: Typed: How are you?
Undo: Typed: Hello, World!
Explanation:
1. Push Operation (Adding Text):
2. Pop Operation (Undoing Action):
3. Handling Empty Stack:
Key Takeaways:
Also Read: What are Data Structures in C & How to Use Them?
Stacks are widely used in many applications, and this stack, which uses a linked list algorithm, will help you efficiently tackle problems like undo functionality.
Next, let’s look at the key operations you can perform on stack.
Now that you understand the knows and hows, let's dive deeper and explore the essential operations that can be performed on stack.
The two main operations on a stack are push and pop.
The push operation inserts an element at the top of the stack. When using a stack using a linked list in C, for example, you create a new node with the element and link it to the top of the stack.
Let’s break down the steps involved:
1. Create a New Node:
When you push an element onto the stack, memory is allocated for a new node, which will hold the value.
2. Link the New Node:
The new node’s next pointer is set to point to the current top node, linking the new node to the stack.
3. Update the Top Pointer:
The top pointer is updated to point to the new node, making it the new top of the stack.
As shown in the diagram above, each new element gets added to the front of the stack, becoming the top element.
Let's implement the push function for a stack implemented using a linked list:
#include <stdio.h>
#include <stdlib.h>
// Define a node structure for the stack
struct Node {
int data; // Stores the data of the node
struct Node* next; // Pointer to the next node in the stack
};
// Define the top of the stack
struct Node* top = NULL;
// Push operation to insert an element at the top
void push(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); // Allocate memory for the new node
if (newNode == NULL) { // Check for memory allocation failure
printf("Memory overflow\n");
return;
}
newNode->data = value; // Set the node's data
newNode->next = top; // Link the new node to the current top node
top = newNode; // Move the top pointer to the new node
printf("Pushed %d to stack\n", value);
}
int main() {
push(15); // Push 15 to the stack
push(87); // Push 87 to the stack
push(24); // Push 24 to the stack
return 0;
}
Output:
Pushed 10 to stack
Pushed 20 to stack
Pushed 30 to stack
Explanation:
The pop operation is used to remove and return the top element of the stack.
Let’s break down the steps involved:
1. Check for Underflow:
First, check if the stack is empty. If it is, print a message indicating no elements are available to pop.
2. Access the Top Node:
Temporarily store the top node to access its data and prepare for removal.
3. Update the Top Pointer:
Move the top pointer to the next node, effectively removing the current top node from the stack.
4. Free the Memory:
After updating the pointer, free the memory occupied by the removed node.
The diagram illustrates how each pop operation removes the topmost node and moves the top pointer to the next node, reducing the stack by one element.
Let's write the pop function to remove the top element:
#include <stdio.h>
#include <stdlib.h>
// Define a node structure for the stack
struct Node {
int data; // Stores the data of the node
struct Node* next; // Pointer to the next node in the stack
};
// Define the top of the stack
struct Node* top = NULL;
// Pop operation to remove the top element from the stack
int pop() {
if (top == NULL) { // Check if the stack is empty
printf("Stack underflow\n");
return -1; // Return a special value to indicate that the stack is empty
}
struct Node* temp = top; // Temporarily store the top node
int poppedValue = temp->data; // Save the data of the top node
top = top->next; // Move the top pointer to the next node
free(temp); // Free the memory of the old top node
return poppedValue; // Return the data of the popped node
}
int main() {
push(15); // Push 15 to the stack
push(87); // Push 87 to the stack
push(24); // Push 24 to the stack
printf("Popped %d from stack\n", pop()); // Pop the top element (24)
printf("Popped %d from stack\n", pop()); // Pop the new top element (87)
printf("Popped %d from stack\n", pop()); // Pop the new top element (15)
return 0;
}
Output:
Pushed 15 to stack
Pushed 87 to stack
Pushed 24 to stack
Popped 24 from stack
Popped 87 from stack
Popped 15 from stack
Explanation:
1. Pop Operation:
2. Underflow Check: Each time we pop, the function checks if the stack is empty (top == NULL). If it is, it prints "Stack underflow" and returns -1.
3. Memory Cleanup: After popping, the memory of the removed node is freed using free(temp), ensuring there are no memory leaks.
Also Read: What Are Storage Classes in C?
In addition to push and pop, you often need to peek at the top element without removing it from the stack.
This operation is often used when you're interested in the current state of the stack, but not necessarily in modifying it.
Let’s look at the steps for Implementing the Peek Operation:
1. Check if the Stack is Empty:
Before peeking, you need to ensure that the stack isn’t empty. If the stack is empty, attempting to peek will result in an error, so the function should handle this case gracefully.
2. Access the Top Element:
If the stack is not empty, the top element can be accessed using the top pointer. You can directly retrieve the data stored in the top node.
3. Return the Value:
Once you access the top element, return it without removing it from the stack.
Let’s walk through how the peek operation can be implemented:
// Peek operation to view the top element of the stack without removing it
int peek() {
if (top == NULL) { // Check if the stack is empty
printf("Stack is empty\n");
return -1;
}
return top->data; // Return the data of the top node without modifying the stack
}
Explanation:
The peek operation simply checks if the stack is empty and returns the data of the top node without removing it, allowing you to view the top element.
The IsEmpty operation is used to check if the stack is empty. This operation is crucial because you want to prevent performing operations like pop or peek on an empty stack, which could lead to errors.
In a stack using a linked list in C, the stack is considered empty when the top pointer is NULL, indicating that there are no elements in the stack.
Let’s start by writing the IsEmpty function to check whether the stack is empty:
#include <stdio.h>
#include <stdlib.h>
// Define a node structure for the stack
struct Node {
int data; // Stores the data of the node
struct Node* next; // Pointer to the next node in the stack
};
// Define the top of the stack
struct Node* top = NULL;
// IsEmpty operation to check if the stack is empty
int isEmpty() {
return top == NULL; // Return true if top is NULL, meaning the stack is empty
}
int main() {
printf("Is stack empty? %d\n", isEmpty()); // Check if the stack is empty
// Pushing elements to the stack
push(10);
push(20);
printf("Is stack empty? %d\n", isEmpty()); // Check if the stack is empty again
return 0;
}
Output:
Is stack empty? 1
Pushed 10 to stack
Pushed 20 to stack
Is stack empty? 0
Explanation:
In a stack using linked list in C, the IsFull operation is usually unnecessary because the stack's size is dynamic, and a linked list does not have a predefined size limit.
However, in an array-based stack, you may need to check whether the stack has reached its maximum size, in which case it is full.
For educational purposes, let’s look at how IsFull would be implemented for an array-based stack:
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 5 // Define the maximum size of the stack
// Define a node structure for the stack
struct Node {
int data; // Stores the data of the node
struct Node* next; // Pointer to the next node in the stack
};
// Define the top of the stack
struct Node* top = NULL;
// IsFull operation for an array-based stack (for reference)
int isFull(int size) {
return size == MAX_SIZE; // Return true if the stack has reached the maximum size
}
int main() {
int size = 0;
// Checking if the stack is full
printf("Is stack full? %d\n", isFull(size));
// Simulating stack operations
size++;
printf("Is stack full? %d\n", isFull(size));
return 0;
}
Output:
Is stack full? 0
Is stack full? 0
Explanation:
Keep exploring different use cases and scenarios to master stack behavior, whether for managing function calls, expression evaluation, or dynamic data.
1. What is the basic unit of a linked list-based stack in C?
a) Array
b) Node
c) Structure
d) Pointer
2. What does the top pointer represent in a stack using linked list?
a) The base of the stack
b) Address of last node
c) Address of the first (top) node
d) Middle of the stack
3. Which operation inserts a new node at the beginning of the linked list stack?
a) Pop
b) Push
c) Traverse
d) Peek
4. What happens in the pop() operation of a linked list-based stack?
a) Last node is removed
b) First node is updated and freed
c) Stack becomes empty
d) Stack overflows
5. Which pointer is updated during a push() operation?
a) A temporary pointer
b) NULL pointer
c) top pointer
d) Head of array
6. What condition indicates that the stack is empty?
a) top == 0
b) top == NULL
c) top == -1
d) top == 1
7. How is dynamic memory allocated for a new node in C?
a) new Node()
b) int *ptr = malloc(size);
c) Node *n = malloc(sizeof(Node));
d) struct Node = malloc(sizeof(int));
8. What is the time complexity of push and pop operations in a linked list stack?
a) O(1)
b) O(n)
c) O(log n)
d) O(n²)
9. A student implements push() but the top doesn’t update. What is most likely missing?
a) Memory allocation
b) Updating the next pointer
c) Assigning new node to top
d) Freeing memory
10. You need to pop an item from a stack. What is the correct order of operations?
a) Access data → update top → free node
b) Free node → update top → print
c) Update pointer → set to NULL
d) Access pointer → reassign base
11. In an interview, you're asked why stack using linked list doesn't overflow. What's the best answer? a) Because pointers can't be full
b) Because memory is allocated dynamically
c) Because arrays aren't used
d) Because top is not NULL
upGrad’s specialized courses on C programming provide a deep dive into topics like stack implementations using linked lists, recursion, and more. With hands-on projects and expert guidance, you will be able to implement stack-based algorithms in real-world applications, improving both your theoretical knowledge and practical coding skills.
Through upGrad’s expert-led curriculum, you’ll learn how to effectively manage dynamic memory, optimize stack operations, and understand the key differences between linked list-based and array-based implementations.
Explore our programs for C programming and data structures:
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
Constant Pointer in C: The Fundamentals and Best Practices
Find Out About Data Structures in C and How to Use Them?
A stack using linked list in C with example allows dynamic memory allocation, meaning the stack can grow or shrink as needed, unlike a fixed-size array.
The stack using linked list algorithm efficiently manages memory by allocating space as elements are pushed and freeing space when they are popped, avoiding memory wastage.
No, a stack using linked list in C with example doesn’t have a fixed size, allowing it to grow or shrink as needed, unlike an array-based stack.
The pop() operation checks if the stack is empty using the isEmpty operation. If the stack is empty, it will return an error message such as "Stack underflow."
The peek() operation returns the data from the top node without removing it, allowing you to view the top element without modifying the stack.
Both push and pop operations have a time complexity of O(1) because they only involve changing the top pointer and adjusting the linked list.
A stack using linked list in C with example allows dynamic resizing, making it more efficient in terms of memory usage compared to a static array-based stack.
The stack using linked list algorithm dynamically allocates memory for each element and frees it when the element is popped, ensuring memory is efficiently used.
Yes, a stack using linked list in C with example is commonly used for tasks like expression evaluation and parsing, as it allows easy push and pop operations for operands and operators.
Yes, you can implement multiple stacks within a single linked list by maintaining separate pointers for each stack, offering memory efficiency and flexibility.
A stack using linked list in C with example is frequently used for undo functionality, expression parsing, function calls, and managing recursion, making it crucial in many real-world applications.
Take a Free C Programming Quiz
Answer quick questions and assess your C programming knowledge
Author|900 articles published
Previous
Next
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
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.