Pages

Custom Search

Friday, November 4, 2011

Program to implement dynamically allocated Stack using linked list.


 #include <stdio.h>  
 #include <stdlib.h>  
 struct tag  
 {  
     int data;  
     struct tag *link;  
 };  
 typedef struct tag * NODE;  
 void push_node();  
 void pop_node();  
 void display();  
 int main()  
 {  
     int ch, element, dnum;  
     NODE top = NULL;  
     do  
     {  
         printf("\n1.) PUSH");  
         printf("\n2.) POP");  
         printf("\n3.) DISPLAY");  
         printf("\n4.) EXIT");  
         printf("\nEnter your choice: ");  
         scanf("%d", &ch);  
         switch(ch)  
         {  
             case 1: printf("\nEnter element to push: ");  
                   scanf("%d", &element);  
                   push_node(&top, element);  
                   break;  
             case 2: pop_node(&top);  
                   break;  
             case 3: display(top);  
                   break;  
             case 4: break;  
             default: printf("\nWrong choice!! Enter choice again.");  
         }  
     }while(ch!=4);  
 }  
 void push_node(NODE *top, int ele)  
 {  
     NODE newnode, temp;  
     temp = *top;  
     newnode = (NODE)malloc(sizeof(struct tag));  
     if(newnode == NULL)  
     {  
         printf("\nInsufficient memory");  
         return;  
     }  
     newnode->data = ele;  
     if(*top == NULL)  
     {  
         newnode->link = NULL;  
         *top = newnode;  
     }  
     else  
     {  
         newnode->link = *top;  
         *top = newnode;  
     }  
 }  
 void pop_node(NODE *top)  
 {  
     NODE c;  
     if(*top == NULL)  
     {  
         printf("\nStack is empty");  
         return;  
     }  
     c=*top;  
     if(c->link == NULL)  
     {  
         printf("\nPopped node: %d", c->data);  
         free(c);  
         *top = NULL;  
         return;  
     }  
     *top = c->link;  
     printf("\nPopped node: %d", c->data);  
     free(c);  
 }  
 void display(NODE top)  
 {  
     NODE temp;  
     temp = top;  
     if(top == NULL)  
     {  
         printf("\nStack is empty");  
         return;  
     }  
     printf("\nStack is: \n");  
     while(temp != NULL)  
     {  
         printf("\n%d", temp->data);  
         temp = temp->link;  
     }  
 }  

No comments:

Custom Search