Implementing Stack using Linked List
Implementing Stack using Linked List
#include<stdio.h>
#include<malloc.h>
struct Node
{
int data;
struct Node *link;
}*start;
void push(int);
void pop();
void display(void);
int main()
{
int num,choice;
start=NULL;
do
{
printf("\n 1.PUSH\n 2.POP\n 3.DISPLAY\n 4.EXIT");
printf("\n Enter the Choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf(" Enter a value to be pushed:");
scanf("%d",&num);
push(num);
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
printf("\n EXIT POINT ");
break;
default:
printf ("\n Invalid Choice");
}
}
while(choice!=4);
return 0;
}
void push(int n)
{
struct Node *newNode,*p;
newNode=(struct Node*)malloc(sizeof(struct Node));
newNode->data=n;
newNode->link=NULL;
if(start==NULL)
{
start=newNode;
}
else
{
p=start;
while(p->link!=NULL)
{
p=p->link;
}
p->link=newNode;
}
}
void pop()
{
struct Node *p,*q;
if(start==NULL)
{
printf("\n Stack is under flow");
}
else if(start->link==NULL)
{
printf("\n The popped elements is %d",start->data);
start=NULL;
}
else
{
p=start;
q=NULL;
while(p->link!=NULL)
{
q=p;
p=p->link;
}
q->link=NULL;
printf("\n The popped elements is %d",p->data);
free(p);
}
}
void display()
{
struct Node *q;
if(start==NULL)
{
printf("\n The STACK is empty");
}
else
{
q=start;
printf("Elements of Stack Is :");
while(q!=NULL)
{
printf("%d ",q->data);
q=q->link;
}
}
}