#include <stdio.h>#include <malloc.h>#include <conio.h>struct Node{ int a; Node *next;};Node* ReverseList( Node ** List );void main(){ struct Node *root,*n,*p; root=(Node*)malloc(sizeof(Node)); root->a=10; root->next=NULL; n=root; p=(Node*)malloc(sizeof(Node)); p->a=20; p->next=NULL; n->next=p; n=p; p=(Node*)malloc(sizeof(Node)); p->a=30; p->next=NULL; n->next=p; n=p; p=(Node*)malloc(sizeof(Node)); p->a=40; p->next=NULL; n->next=p; n=p; p=(Node*)malloc(sizeof(Node)); p->a=50; p->next=NULL; n->next=p; n=p; Node *rlist = ReverseList(&root); int i=1; while(rlist!=NULL){ printf("element %d =%dn",i++,rlist->a); rlist=rlist->next; } n=root; while(n!=NULL){ p=n->next; free(n); n=p; }}Node* ReverseList( Node ** List ){ Node *temp1 = *List; Node * temp2 = NULL; Node * temp3 = NULL; while ( temp1 ) { *List = temp1; //set the head to last node temp2= temp1->next; // save the next ptr in temp2 temp1->next = temp3; // change next to privous temp3 = temp1; temp1 = temp2; } return *List;}
Please Note: We keep on updating better answers to this site. Subscribe to our newsletter to get notified when better answer is posted.
Copyright ©2003-2010 CoolInterview.com, All Rights Reserved. Privacy Policy | Terms and Conditions Page URL: http://www.coolinterview.com/interview/5943/default.asp?cachecommand=bypass