Stack using linked list

Leave a Comment
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>

struct node{
int n;
struct node *next;
};
struct node *top=NULL;


void push()
{
struct node *k;
k=(struct node*)malloc(sizeof(struct node));
if(top==NULL)
{
printf("\nEnter the element:");
scanf("%d",&k->n);
k->next=NULL;
top=k;
}
else
{
printf("\nEnter the element:");
scanf("%d",&k->n);
k->next=top;
top=k;
}
}


void pop()
{
if(top==NULL)
printf("\nThe stack is empty!!");
else
{
printf("\nThe element popped is %d",top->n);
top=top->next;
}
}


void display()
{
struct node *k;
k=(struct node*)malloc(sizeof(struct node));
printf("\nThe stack is\n");
k=top;
while(k!=NULL)
{
printf("%d\n",k->n);
k=k->next;
}
}
void isempty()
{
if(top==NULL)
printf("\nThe stack is empty!!");
}


void peek()
{
printf("\nThe peak element in the stack is %d",top->n);
}



int main()
{
int o;
while(o!=0)
{

printf("\nMENU");
printf("\n1 for PUSH");
printf("\n2 for POP");
printf("\n3 for PRINT");
printf("\n4 for CHECKING EMPTY");
printf("\n5 for SEEKING TOP ELEMENT");
printf("\n0 for EXIT");
printf("\nEnter ur choice");
scanf("%d",&o);
switch(o)
{
case 1:push();break;
case 2:pop();break;
case 3:display();break;
case 4:isempty();break;
case 5:peek();break;
case 0:exit(0);break;
default:printf("\nU have entered a wrong choice!!!");
}
}
getche();
}

0 comments: