DATA STRUCTURES PROGRAM • STACKS & EXPRESSIONS
Implement a Stack Using a Linked List
Learn how to implement a stack using a linked list using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
Popped = 30 Top = 20
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
#include <stdlib.h>
struct Node { int data; struct Node *next; };
void push(struct Node **top, int value)
{
struct Node *node = malloc(sizeof *node);
if (node == NULL) exit(EXIT_FAILURE);
node->data = value; node->next = *top; *top = node;
}
int pop(struct Node **top)
{
if (*top == NULL) { puts("Stack underflow."); exit(EXIT_FAILURE); }
struct Node *removed = *top; int value = removed->data;
*top = removed->next; free(removed); return value;
}
int main(void)
{
struct Node *top = NULL;
push(&top, 10); push(&top, 20); push(&top, 30);
printf("Popped = %d\n", pop(&top));
printf("Top = %d\n", top->data);
while (top != NULL) pop(&top);
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Popped = 30 Top = 20
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Treat the list head as the stack top for constant-time insertion and deletion.
- Display the computed result.
Treat the list head as the stack top for constant-time insertion and deletion.
EFFICIENCY
Time and space complexity
Time complexity
O(1) per operation
Auxiliary space
O(n)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
