Monday 23 February 2015

Stack Program in C


#include<stdio.h>
#include<conio.h>

struct Stack
{
int Data;
struct Stack *Next;
}*Top;

main()
{
int choice;
Home:
clrscr();
printf("\n\t\t\t Stack Demo \n");
printf("\n\t\t\t1.. Push");
printf("\n\t\t\t2.. Pop");
printf("\n\t\t\t3.. Display");
printf("\n\t\t\t4.. Exit");
printf("\n\n\t\t Enter Your Choice\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
Push();
break;
case 2:
Pop();
break;
case 3:
Display();
break;
case 4:
exit(0);
case 5:
printf("\n Wrong Press");
}
goto Home;
}

Push()
{
struct Stack *Source=(struct Stack*)malloc(sizeof(struct Stack));

printf("\n Enter Data For Stack\n");
scanf("%d",&Source->Data);
Source->Next=NULL;

if(Top==NULL)
{
Top=(struct Stack*)malloc(sizeof(struct Stack));
Top=Source;
}
else
{
Source->Next=Top;
Top=Source;
}
}
Pop()
{
struct Stack *Source=(struct Stack*)malloc(sizeof(struct Stack));
Source=Top;
if(Source==NULL)
{
printf("\n Stack Is Empty");
}
else
{
printf("\n Poped Item is :%d",Source->Data);
Top=Top->Next;
free(Source);
}
getch();
}
Display()
{
struct Stack *Source=(struct Stack*)malloc(sizeof(struct Stack));
Source=Top ;
while(Source!=NULL)
{
printf("\n Stack Item is :%d",Source->Data);
Source=Source->Next;
}
getch();
}

No comments:

Post a Comment