/*Serial No.141 [swami123.cpp]*/
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
typedef struct node
{
int info;
struct node *next;
}node;
void push(node **head)
{
node *q=*head,*temp;
temp=(node*)malloc(sizeof(node));
printf("\nEnter the element to insert= ");
scanf("%d",&temp->info);
temp->next=NULL;
if(q==NULL)
{
*head=temp;
return;
}
else
{
while(q->next!=NULL)
{
q=q->next;
}
q->next=temp;
}
}
void display_stack(node *head)
{
if(head==NULL)
printf("\nStack is empty.");
else
{
do
{
printf("%d ",head->info);
head=head->next;
}while(head!=NULL);
}
}
void pop(node **head)
{
node *q=*head,*temp;
if(*head==NULL)
{
printf("\nStack is empty. You can't pop.");
return;
}
else if(q->next==NULL)
{
temp=q;
*head=NULL;
printf("\nvalue poped=%d ",q->info);
}
else
{
while(q->next->next!=NULL)
{
q=q->next;
}
temp=q->next;
printf("\nvalue poped=%d ",q->next->info);
q->next=NULL;
}
free(temp);
}
void main()
{
int choice;
node *start=NULL;
clrscr();
do
{
printf("\n\t[1] Push");
printf("\n\t[2] Pop");
printf("\n\t[3] Display");
printf("\n\t[7] Exit");
printf("\nEnter your choice= ");
scanf("%d",&choice);
switch(choice)
{
case 1: push(&start);
break;
case 2: pop(&start);
break;
case 3: display_stack(start);
}
}while(choice!=7);
getch();
}
No comments:
Post a Comment
If you have any doubt, feel free to ask...