write a program to reverse a linked list in linear time
Anonym
#include #include struct link{ int data; struct link *ptr; }; struct link *head; void insert(int no){ struct link *temp=(struct link*)malloc(sizeof(struct link)); struct link *prev; temp->data=no; temp->ptr=NULL; if(head==NULL){ head=temp; prev=temp; return; } prev->ptr=temp; prev=temp; } void printIt(){ struct link *temp=head; while(temp!=NULL){ printf("%d\n",temp->data); temp=temp->ptr; } } void reverse(){ struct link *temp=head; struct link *prev=NULL; struct link *sprev=NULL; while(temp!=NULL){ if(prev!=NULL) prev->ptr=sprev; sprev=prev; prev=temp; temp=temp->ptr; } prev->ptr=sprev; head=prev; } int main(){ insert(5); insert(7); insert(1); insert(4); insert(8); insert(9); printIt(); printf("Now reverse\n"); reverse(); printIt(); }