Saturday, 8 February 2014

problem statement: Given n, display nth node in a list in C.


 problem statement: Given n, display nth node in a list 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 displaynthnode(int pos)  
 {  
   struct node *start , *move;  
   start = move = root;  
   int cnt = 0;  
   while(cnt != pos-1)  
   {  
     move = move->link;  
     cnt++;  
   }  
   while(move->link!=NULL)  
   {  
     start = start->link;  
     move = move->link;  
   }  
   printf("\nElement at %d position is:%d\n",pos,start->data);  
 }  
 int main()  
 {  
   int pos;  
   addNode(4);  
   addNode(14);  
   addNode(54);  
   addNode(1);  
   addNode(23);  
   addNode(89);  
   addNode(56);    
   addNode(30);  
   addNode(55);  
   addNode(100);  
   printf("\nEnter the element position:");  
   scanf("%d",&pos);  
   displaynthnode(pos);  
 }  

No comments:

Post a Comment