C program to implement stack using linked list


/* C program to implement stack using linked list */
/* By Nishi */

#include<stdio.h>

#include<stdlib.h>

struct  node

{

int data;

struct node *link;

}*q,*header=NULL,*p;

typedef struct node N;

void push()

{

int n;

printf("\nEnter a number to push :");

scanf("%d",&n);

p=(N *)malloc(sizeof(N));

p->data=n;

if(header==NULL)

{
p->link=NULL;

header=p;

view();

}

else

{

p->link=header;

header=p;

view();
}

}

void pop()

{

if(header==NULL)

printf("\n---Stack Empty---\n");

else

{

p=(N *)malloc(sizeof(N));

p=header;

header=header->link;

free(p);

view();

}

}

view()

{

q=(N *)malloc(sizeof(N));

q=header;

if(q==NULL)
{

printf("\n---Stack empty---\n");

}

else{
printf("\n-------------------STACK---------------------------\n");

while(q!=NULL)

{

printf("%d ",q->data);
q=q->link;
}
printf("\n---------------------------------------------------\n");

}

}

main()

{

int c;

while(1)
{

printf("\n1. PUSH   2. POP   3. VIEW   4. EXIT\nEnter : ");

scanf("%d",&c);

switch(c)

{

case 1:push();
break;
case 2:pop();
break;
case 3:view();
break;
case 4:exit(0);
break;
default:printf("\nUnknown Command\n");
break;

}

}

}

/* By Nishi */

Comments