Write a code to implement stack program in C using linked list. In this tutorial, You are going to learn how to implement stack data structure using linked list.
In my previous post, I have explained Stack program in c using array.
Stack Data Structure
Let’s revise some of the terminologies of a stack.
i) Stack worked on LIFO (Last In First Out) Principle. It means insertion and deletion are allowed only at one end. The element which added last must be the first element to be removed.
ii) In Stack, Insertion operation is called Push and deletion operation is called Pop . During push operation if memory is not available then it’s termed as StackOverflow. During pop operation if a stack is empty, then it’s called StackUnderflow
MCQ on Stack and Queue Data Structure.
Stack Program in C using Linked List
I assumed you have a basic understand of linked list. If you are not familiar with linked list data structure then check my previous posts on linked list.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
#include <stdio.h> #include <stdlib.h> /* Create a node which contains data and next pointer link */ struct node{ int data; struct node *link; }; struct node *head; void push(int data){ /* Allocate memory */ struct node *newNode = (struct node*)malloc(sizeof(struct node)); /* If memory is full */ if (newNode == NULL) { printf("Stack Overflow \n"); return; } /* Create new node */ newNode->data = data; newNode->link = head; head = newNode; } void pop() { /* If there is no element to pop */ if(head == NULL) { printf("Stack Underflow"); exit(0); } struct node *p = head; int data; data = p->data; /* Points to next link */ head = head->link; free(p); printf("Popped element is %d\n",data); } main() { /*Initially head is assigned null. */ head = NULL; push(4); push(6); pop(); push(8); pop(); } |
Output
Popped element is 6
Popped element is 8
Explanation
In this program first, we pushed element 4 and 6 in a stack. Stack worked on LIFO(Last In First Out) principle. Then a pop method is called, so 6 is popped out. Again we push element 8 and then we called a pop method which popped 8 from a stack.