Sunday, October 2, 2011

Data Structure C program stack using linked list Dev c++


Data Structures in C Program Linked List Stack


 #include <stdio.h>  
 struct stack{  
     int data;  
     struct stack* next;  
     };  
 typedef struct stack* node;  
 void push(node);  
 int pop();  
 node top=NULL;  
 void push(node temp)  
 {  
    if(top==NULL)//if inserting first elsement  
    {  
     top=temp;//|value||null(top)|  
     top->next=NULL;  
    }  
    else//general case  
    {  
      temp->next=top;  
      top=temp;  
      //|newvalue(TOP)||->|value||NULL|  
      /*new element becomes new top*/  
    }  
 }  
 int pop()  
 {  
   node temp;  
   int x;  
   if(top==NULL)//if top is null   
   {  
    printf("Stack Empty\n");  
   }  
   else  
   {  
     temp=top;  
     x=temp->data;  
     top=top->next;  
     free(temp);  
   }  
   return x;  
 }  
 void display()  
 {  
  node temp;  
  if(top==NULL)  
  {  
    printf("empty stack\n");  
  }  
  else  
  {  
    temp=top;  
    printf("Stack is:-\n");  
    while(temp!=NULL)  
    {  
      printf("%d\n",temp->data);  
      temp=temp->next;  
    }  
  }  
 }  
 int main()  
 {  
   int ch;  
   printf("1.Push\n2.Pop\n3.Display\n4.Exit\n");  
   scanf("%d",&ch);  
   node temp;  
   int x;  
   while(ch!=4)  
   {  
    switch(ch)  
    {  
     case 1:  
         temp=(struct stack*)malloc(sizeof(struct stack));  
         printf("Enter data:");  
         scanf("%d",&(*temp).data);  
         push(temp);  
         break;  
     case 2:  
         x=pop();  
         printf("Removed %d\n",x);  
         break;  
     case 3:  
         display();  
         break;  
     default:printf("WRONG CHOICE ENTER AGAIN\n");  
    }  
    printf("1.Push\n2.Pop\n3.Display\n4.Exit\n");  
    scanf("%d",&ch);  
   }  
 }  

No comments:

Post a Comment