For working professionals
For fresh graduates
More
Explore C Tutorials: From Begi…
1. Introduction to C Tutorial
2. Addition of Two Numbers in C
3. Anagram Program in C
4. Armstrong Number in C
5. Array in C
6. Array of Pointers in C
7. Array of Structure in C
8. C Program to Find ASCII Value of a Character
9. Assignment Operator in C
10. Binary Search in C
11. Binary to Decimal in C
12. Bitwise Operators in C
13. Boolean in C
14. C Compiler for Mac
15. C Compiler for Windows
16. C Function Call Stack
17. C Language Download
18. Operators in C
19. C/C++ Preprocessors
20. C Program for Bubble Sort
21. C Program for Factorial
22. C Program for Prime Numbers
23. C Program for String Palindrome
24. C Program to Reverse a Number
25. Reverse a String in C
26. C string declaration
27. String Input Output Functions in C
28. Calculator Program in C
29. Call by Value and Call by Reference in C
30. Ceil Function in C
31. Coding Vs. Programming
32. Command Line Arguments in C/C++
33. Comments in C
34. Compilation process in C
35. Conditional Statements in C
36. Conditional operator in the C
37. Constant Pointer in C
38. Constants in C
39. Dangling Pointer in C
40. Data Structures in C
41. Data Types in C
42. Debugging C Program
43. Convert Decimal to Binary in C
44. Define And include in C
45. Difference Between Arguments And Parameters
46. Difference Between Compiler and Interpreter
47. Difference Between If Else and Switch
48. Do While Loop In C
49. Double In C
50. Dynamic Array in C
51. Dynamic Memory Allocation in C
52. Enumeration (or enum) in C
53. Evaluation of Arithmetic Expression
54. Factorial of A Number in C
55. Features of C Language
56. Fibonacci Series Program in C Using Recursion
57. File Handling in C
58. For Loop in C
59. Format Specifiers in C
60. Functions in C
61. Function Pointer in C
62. goto statement in C
63. C Hello World Program
64. Header Files in C
65. Heap Sort in C Program
66. Hello World Program in C
67. History of C Language
68. How to compile a C program in Linux
69. How to Find a Leap Year Using C Programming
70. Identifiers in C
71. If Else Statement in C
72. If Statement in C
73. Implementation of Queue Using Linked List
74. Increment and decrement operators in c
75. Input and Output Functions in C
76. How To Install C Language In Mac
77. Jump Statements in C
78. Lcm of Two Numbers in C
79. Length of an Array in C
80. Library Function in C
81. Linked list in C
82. Logical Operators in C
83. Macros in C
84. Matrix multiplication in C
85. Nested if else statement in C
86. Nested Loop in C
87. One Dimensional Array in C
88. Operator Precedence and Associativity in C
89. Overflow And Underflow in C
90. Palindrome Program in C
91. Pattern Programs in C
92. Pointer to Pointer in C
93. Pointers in C: A Comprehensive Tutorial
94. Pre-increment And Post-increment
95. Prime Number Program in C
96. Program for Linear Search in C
97. Pseudo-Code In C
98. Random Access Files in C
99. Random Number Generator in C
100. Recursion in C
101. Relational Operators in C
102. Simple interest program in C
103. Square Root in C
104. Stack in C
105. Stack Using Linked List in C
Now Reading
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
112. String Comparison in C
113. String Functions in C
114. String Length in C
115. String Pointer in C
116. strlen() in C
117. Structures in C
118. Structure of C Program
119. Switch Case in C
120. C Ternary Operator
121. Tokens in C
122. Toupper Function in C
123. Transpose of a Matrix in C
124. Two Dimensional Array in C
125. Type Casting in C
126. Types of Error in C
127. Unary Operator in C
128. Use of C Language
129. User Defined Functions in C
130. What is Variables in C
131. Is C language case sensitive
132. Fibonacci Series in C
A stack data structure operates on the LIFO (Last In, First Out) principle. Elements are added and removed from the top, making it perfect for scenarios like undo operations in applications, where you need quick access to the most recently added item.
For beginners, managing a stack with a linked list algorithm can be tricky, especially when it comes to implementing operations like push and pop effectively.
In this guide, you’ll learn how to implement a stack using a linked list in C with examples and how to handle the operations seamlessly. Let’s dive into the details!
Boost your C programming skills with our Software Development courses— take the next step in your learning journey!
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.
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.
Ready to put your knowledge of stack operations to the test? This quiz will help you assess your understanding of stacks implemented using linked lists in C programming.
1. What is the primary advantage of using a linked list to implement a stack in C?
A) Easier to manage memory
B) It does not have a fixed size
C) Faster push/pop operations
D) It is slower than array-based stacks
2. In a stack implemented using a linked list, where are the elements inserted?
A) At the bottom of the stack
B) In the middle of the stack
C) At the top of the stack
D) In any random position
3. What does the "top" pointer in a stack using a linked list point to?
A) The first element in the stack
B) The most recently added element
C) The last element in the stack
D) The second element from the top
4. Which operation is used to add an element to the stack in a linked list implementation?
A) pop()
B) push()
C) insert()
D) add()
5. Which of the following is a key advantage of a stack implemented using a linked list over an array implementation?
A) Fixed memory usage
B) Dynamic memory allocation
C) Simpler code
D) Faster element access
6. What will happen if you attempt to pop from an empty stack implemented using a linked list?
A) Stack underflow
B) Stack overflow
C) Program will crash
D) No operation
7. What is the time complexity of the push and pop operations for a stack implemented using a linked list?
A) O(n)
B) O(1)
C) O(log n)
D) O(n^2)
8. What is the typical data structure used to implement the stack using linked list?
A) Arrays
B) Pointers
C) Hash maps
D) Queues
9. Which of the following operations is typically done in constant time (O(1)) in a stack using linked list?
A) Insertion of a new element
B) Searching for an element
C) Deleting an element from the middle
D) Sorting the stack
10. How does memory management work in a stack using a linked list?
A) The memory size is fixed during stack creation
B) The memory is dynamically allocated and freed after each operation
C) Memory is allocated at the end of the program
D) It does not require memory management
Understanding factorial calculations is just the beginning—keep building your C programming skills with expert-led courses and hands-on learning.
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
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
+918045604032
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.