Saturday, 28 April 2012

Linked List Implementation of Stacks in C

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

struct s
{
 int data;
 struct s *next;
};
struct s *pop(struct s *top);
struct s *push(struct s *top);

int main()
{
 struct s *top;
 int x,choice,data;
 clrscr();
 
 top = NULL;
 do
 {
  printf("\n 1. Push");
  printf("\n 2. Pop");
  printf("\n 3. Exit");
  printf("\nEnter Your Choice : " );
  scanf("%d",&choice);
  switch(choice)
  {
   case 1 :
    top = push(top);
    break;
   case 2 :
    top = pop(top);
   break;
   case 3 : exit(0);
  }
 }while(1);
}

struct s *push(struct s *top)
{
 struct s *c;
 
 c = (struct s*)malloc(sizeof(struct s));
 if( c == NULL)
 {
  printf("Insuff. mem");
  return(top);
 }
 printf("\nEnter data : ");
 scanf("%d",&c->data);
 c->next = NULL;
 if( top == NULL)
  top = c;
 else
 {
  c->next = top;
  top = c;
 }
 return(top);
} 

struct s *pop(struct s *top)
{
 struct s *c;
 if( top == NULL)
 {
  printf("Stack is empty");
  return(top);
 }
 printf("\npopped data : %d",top->data);
 c = top;
 top = top->next;
 free(c);
 return(top);
}

No comments:

Post a Comment