Sunday, April 1, 2012

stack using linkedlist


#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));
}




No comments:

Post a Comment