Saturday, 8 February 2014

Problem statement: Find a mid of list in single traversal in C


 #include<stdio.h>  
 struct node  
 {  
   int data;  
   struct node *link;  
 };  
 struct node *root;  
 void addNode(int val)  
 {  
   struct node *temp = (struct node *)malloc(sizeof(struct node));  
   temp->data = val;  
   temp->link = NULL;  
   if(root == NULL)  
   {  
     root = temp;  
     printf("%d\n",root->data);  
   }    
   else  
   {  
     struct node *ptr = root;  
     while(ptr->link !=NULL)  
     {  
       ptr = ptr->link;  
     }  
     ptr->link = temp;  
     printf("%d\n",ptr->link->data);  
   }  
 }  
 void findmid()  
 {  
   struct node *start , *end;  
   start = end = root;  
   while(end->link !=NULL)  
   {  
     start = start->link;  
     end = end->link;  
     if(end->link!=NULL)  
       end = end->link;  
   }  
   printf("\nMid element is %d\n",start->data);    
 }  
 int main()  
 {  
   addNode(4);  
   addNode(14);  
   addNode(54);  
   addNode(1);  
   addNode(23);  
   addNode(89);  
   addNode(56);    
   addNode(30);  
   addNode(55);  
   addNode(100);  
   //addNode(77);  
   findmid();  
 }  

No comments:

Post a Comment