In this C program we will perform Stack operations using Linked List.color>
input:
The Choice(i.e Push,Pop,Display) & The Number (integers) (i.e. for Push) (15,10,128 etc.)output:
The Operations will be excecuted as choosen by the user.CODE---->
#include
typedef struct node{
#include
#include
int data;
struct node *next;
}node;
node *top;
void push(int data)
{
node *head,*afterhead;
head=(node *)malloc(sizeof(node));
if(head==NULL)
{
printf("\nMemory cant be allocated.");
exit(0);
}
head->data=data;
head->next=NULL;
if(top==NULL)
top=head;
else
{
afterhead=top;
top=head;
head->next=afterhead;
}
}
void pop()
{
node *ptr;
if(top==NULL)
{
printf("\nStack Underflow.");
exit(0);
}
else
{
ptr=top;
printf("\n%d is Popped from Stack.",ptr->data);
top=top->next;
free(ptr);
}
}
void display()
{
node *pos;
if(top==NULL)
printf("\nNo element exists.");
else
{
pos=top;
while(pos!=NULL)
{
printf(" %d ",pos->data);
pos=pos->next;
}
}
}
void main()
{
int choice,item;
while(1)
{
printf("\n==========Menu==========\n");
printf("\n1.Push\n2.Pop\n3.Display\n4.Exit");
printf("\n\nEnter Your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("\nEnter data : ");
scanf("%d",&item);
push(item);
break;
case 2: pop();
break;
case 3: display();
break;
case 4: exit(0);
break;
default : printf("\nWrong choice.");
}
}
}
Download the C-Program file of this Program.
RESULT :color>
==========Menu==========
1.Push
2.Pop
3.Display
4.Exit
Enter Your choice : 1
Enter data : 10
==========Menu==========
1.Push
2.Pop
3.Display
4.Exit
Enter Your choice : 1
Enter data : 20
==========Menu==========
1.Push
2.Pop
3.Display
4.Exit
Enter Your choice : 1
Enter data : 30
==========Menu==========
1.Push
2.Pop
3.Display
4.Exit
Enter Your choice : 3
30 20 10
==========Menu==========
1.Push
2.Pop
3.Display
4.Exit
Enter Your choice : 2
30 is Popped from Stack.
==========Menu==========
1.Push
2.Pop
3.Display
4.Exit
Enter Your choice : 4
--------------------------------
Process exited after 23.15 seconds with return value 0
Press any key to continue . . .
Images for better understanding : color>