Saturday, 31 December 2011

Implementation of Stacks using Linked Lists


#include<stdio.h>
#include<stdlib.h>

typedef struct node
{
 int data;
 struct node *link;
}NODE,*NODEPTR;

NODEPTR insert(NODEPTR start)
{
 NODEPTR temp;
 temp=(NODEPTR)malloc(sizeof(NODE));
 if(temp==NULL)
 {
  printf("Unsuccessfull\n");
  return;
 }
 temp->link=NULL;
 printf("Enter the data to be pushed\n");
 scanf("%d",&temp->data);
 temp->link=start;
 start=temp;
 return start;
}

NODEPTR del(NODEPTR start)
{
 NODEPTR temp;
 if(start==NULL)
 {
  printf("Stack is empty\n");
  return;
 }
 temp=start;
 start=start->link;
 printf("The element popped is %d\n",temp->data);
 free(temp);
 return start;
}

void dis(NODEPTR start)
{
 NODEPTR temp;
 if(start==NULL)
 {
   printf("Stack is empty\n");
   return;
 }
 printf("The contents of the stack are:\n");
 for(temp=start;temp!=NULL;temp=temp->link)
  printf("%d\n",temp->data);
 }

main()
{
 int ch;
 NODEPTR start=NULL;
 while(1)
 {
  printf("1.Push\n2.Pop\n3.Display\n4.Exit\n");
  scanf("%d",&ch);
  switch(ch)
 {
  case 1 : start=insert(start);
           break;
  case 2 : start=del(start);
            break;
  case 3 : dis(start);
           break;
  default: return;
 }
}
}

No comments:

Post a Comment