Saturday 8 February 2014

Problem statement: Reverse a list in single traversal in C


 #include<stdio.h>  
 struct node  
 {  
   int data;  
   struct node *link;  
 };  
 void addNode(int data,struct node **rt)  
 {  
   struct node *temp=(struct node *)malloc(sizeof(struct node));  
   temp->data = data;  
   temp->link = (*rt);  
   (*rt)=temp;  
   printf("%d\n",(*rt)->data);  
 }  
 struct node *reverse(struct node **rt)  
 {  
   struct node *prev,*curr,*next;  
   prev= NULL;  
   curr=(*rt);  
   while(curr!=NULL)  
   {  
     printf("%d\n",curr->data);  
     next = curr->link;  
     curr->link=prev;  
     prev=curr;  
     curr=next;  
   }  
   return prev;  
 }  
 int main()  
 {  
   struct node *root=(struct node *)malloc(sizeof(struct node));  
   root->data = -1;  
   root->link=NULL;  
   addNode(5,&root);  
   addNode(4,&root);  
   addNode(9,&root);  
   addNode(1,&root);  
   addNode(3,&root);  
   addNode(8,&root);  
   addNode(10,&root);  
   addNode(13,&root);  
   addNode(2,&root);  
   struct node *head=(reverse(&root))->link;  
   while(head!=NULL)  
   {  
     printf("%d->",head->data);  
     head=head->link;  
   }  
 }  

No comments:

Post a Comment