Simulation of Stack using a Linked List

#include<stdio.h>
#include<conio.h>
typedef struct node
{
    int data;
    struct node *next;
} node;
node * init();
int empty(node *top);
int gettop(node *top);//get the value of the topmost data
node *  Delete(node *);//deletes the front element
node *  insert(node *top ,int x);//insert an element x at the front
void print(node  *top);
void main()
{
    node *top;
    int x,op;
    top=init();
    clrscr();

    do {
         printf("\n\n1)Push\n2)Pop\n3)Print\n4)Quit");
         printf("\nEnter Your choice: ");
         scanf("%d",&op);
         switch(op)
          { case 1:printf("\n enter a number :");
               scanf("%d",&x);
               top=insert(top,x);
               break;
           case 2:if(!empty(top))
             {
                x=gettop(top);
                printf("\npopped value= %d",x);
                top=Delete(top);
             }
               else
                printf("\nStack is empty.....");
               break;

           case 3:print(top);break;
         }
      }while(op!=4);

}
node * init()
{
      return(NULL);
}
int empty(node  *top)
{
    if(top==NULL)
        return(1);
    return(0);
}
node * insert(node *top,int x)
{
    node  *p;
    p=(node*)malloc(sizeof(node));
    p->data=x;
    p->next=top;
    return(p);
}
int gettop(node *top)
 {
   int x;
   x=top->data;
   return(x);
 }
node* Delete(node *top)
{
    node *p;
    p=top;
    top=top->next;
    free(p);
    return(top);
}
void print(node *p)
 {
    printf("\n");
    while(p!=NULL)
       {
        printf("%d  ",p->data);
        p=p->next;
       }
}

Post a Comment

0 Comments