#include< stdio.h>
typedef struct stack
{
int data;
struct stack *next;
}list;
list *push(list *);
list *pop(list *);
void display(list *);
int count(list *);
int menu(list *);
void main()
{
int choice;
list *tos;
tos=(list *)malloc(sizeof(list));
tos->next=NULL;
while(1)
{
choice=menu(tos);
switch(choice)
{
case 1: tos=push(tos);
break;
case 2: tos=pop(tos);
getch();
break;
case 3: printf("\ndisplaying current stack : \n\n");
display(tos);
getch();
break;
case 4: exit();
default: printf("\ninvalid option... \n");
getch();
}
}
}
int menu(list *tos)
{
int a=0;
clrscr();
printf("no of elements in stack: %d\ncurrent stack : \n\n",count(tos));
display(tos);
printf("\n\nMENU\n-------------\n");
printf("1. push\n2. pop\n3. display\n4. exit\nenter an option : ");
scanf("%d",&a);
return a;
}
list *push(list *tos)
{
list *temp;
int element;
temp=(list *)malloc(sizeof(list));
if(temp==NULL)
{
printf("\nInsufficient memory...\n");
getch();
exit();
}
else
{
printf("\nenter element to push : ");
scanf("%d",&element);
temp->data=element;
temp->next=tos;
tos=temp;
}
return (tos);
}
list *pop(list *tos)
{
list *temp;
if(tos->next!=NULL)
{
temp=tos->next;
free(tos);
tos=temp;
printf("\nelement poped from stack\n");
}
else
printf("\nStack is Empty...\n");
return (tos);
}
void display(list *tos)
{
list *temp;
temp=tos;
if(temp->next==NULL)
printf("\nStack is Empty...\n");
else
{
while(temp->next!=NULL)
{
printf("%d ",temp->data);
temp=temp->next;
}
}
}
int count(list *tos)
{
if(tos->next==NULL)
return 0;
else
return (1+count(tos->next));
}
Sunday, April 1, 2012
stack using linkedlist
stack using array
#include< stdio.h>
int stack[10],top,element,choice;
void push();
void pop();
void display();
int menu();
int empty();
void main()
{
top=-1;
while(1)
{
choice=menu();
switch(choice)
{
case 1: push();
getch();
break;
case 2: pop();
getch();
break;
case 3: printf("\nno. of stack elements : %d\ndisplaying current stack :\n\n",top+1);
display();
getch();
break;
case 4: exit();
default: printf("\ninvalid option... \n");
getch();
}
}
}
int menu()
{
int a=0;
clrscr();
printf("Stack of 10 elements : \n\n");
display();
printf("\n\nMENU\n-------------\n");
printf("1. push\n2. pop\n3. display\n4. exit\nenter an option : ");
scanf("%d",&a);
return a;
}
void push()
{
if(empty()==0)
return;
else
{
top++;
printf("\nenter element to push : ");
scanf("%d",&element);
stack[top]=element;
}
}
void pop()
{
if(empty()==1)
return;
else
{
top--;
printf("\nelement poped from stack\n");
}
}
void display()
{
int temp;
temp=top;
if(empty()==1)
return;
else
{
while(temp>-1)
{
printf("%d ",stack[temp]);
temp--;
}
}
}
int empty()
{
if(top==-1)
{
printf("\nstack is empty\n");
return 1;
}
else if(top>9)
{
printf("\nstack is full\n");
return 0;
}
else
return 5;
}
Subscribe to:
Posts (Atom)