Menu Close

Stack Using Linked List Program

  • This program explains how to implement Stack using Single linked List.
  • We implement 3 Stack operations Push() , Pop() and Traverse()
#include<stdio.h>
#include <stdlib.h>
struct node
{
    int data;
    struct node* link;
};
struct node *top;
void push();
void pop(void);
void traverse(void);
void main(void)
{
    int ch , ele;
    while(1)
    {
        printf("1.Push \n");
        printf("2.Pop \n");
        printf("3.Traverse \n");
        printf("4.Quit \n");
        
        printf("Enter choice : ");
        scanf("%d", &ch);
        
        switch(ch)
        {
            case 1   :  push();
                        break ;
                        
            case 2   :  pop();
                        break;
                        
            case 3   :  traverse();
                        break;
                        
            case 4   :  exit(1);
            
            default  :  printf("Invalid choice\n\n");
        }
    }
}

void push()
{
    struct node*temp=(struct node*)malloc(sizeof(struct node));
    if(temp==NULL)
    {
        printf("No memory\n\n");
    }
    else
    {
        printf("Enter element to push :");
        scanf("%d",&temp->data);
        temp->link=top;
        top=temp;
    }    
}

void pop(void)
{
    if(top == NULL)
    {
        printf("Stack is underflow\n\n");
    }
    else
     {
         struct node* temp=top;
         top=temp->link;
         temp->link=NULL;
        printf("Element popped is :%d\n\n",temp->data);
         free(temp);
     }
}

void traverse(void)
{
    if(top==NULL)
    {
        printf("Stack is empty\n\n");
    }
    else
    {
        struct node* temp=top;
        while(temp!=NULL)
        {
              printf("%d\n",temp->data);
              temp=temp->link;
        }
    }    
}