Stack in C using linked list


We learned about linked list. It is a collection of similar element and each element is having a address of next element. We can also create a stack using linked list. Stack is simply a LIFO.

LIFO stands for LAST IN FIRST OUT.

Create a node using structure

struct node{
    int data;
    struct node *next; 
    };

How to push data inside the stack

  • Create a function named Push() which takes address of node pointer as an argument(i.e pointer to pointer of node).
  • Create a node and allocate it memory using malloc.
  • Now add a link from new node to old stack.
  • Update the value of top.
void push(struct node **top, int data){
    struct node *temp;
    temp = (struct node*) malloc(sizeof(struct node));
   temp->data = data;
   temp ->next = *top;
   *top = temp;
}

How to display the data

  • Traverse through the stack using for loop and keep on displaying the data.
  • Increment the link each time.
void display(struct node *p){
    while(p!=NULL){
        printf("%d", p->data);
        p = p->next;
    }   
}

How to pop the node from stack

  • Assign the pointer to first node to temp variable.
  • Increment the link of temp variable.
  • Assign the new top.
void pop(struct node **top){
    struct node *temp;
    temp = *top;
    temp = temp->next;
    *top = temp;
    
}

Complete code

#include <stdio.h>
#include <string.h>
#include <malloc.h>
struct node{
    int data;
    struct node *next; 
    };
void push(struct node**, int data); 
void pop(struct node**);
void display(struct node*);
main()
{
   struct node *p;
   p = NULL;
   push(&p, 5);
   push(&p, 7);
   push(&p, 3);
   printf("before pop");
   display(p);
   pop(&p);
   printf("after first pop");
   display(p);
   pop(&p);
   printf("after second pop");
   display(p);
}
void push(struct node **top, int data){
    struct node *temp;
    temp = (struct node*) malloc(sizeof(struct node));
   temp->data = data;
   temp ->next = *top;
   *top = temp;
}
void pop(struct node **top){
    struct node *temp;
    temp = *top;
    temp = temp->next;
    *top = temp;
    
}
void display(struct node *p){
    while(p!=NULL){
        printf("\n%d\n", p->data);
        p = p->next;
    }
    
}

Output :

In the next tutorial we will learn some more operations related to stack. We will also implement stack using array.