c - Reverse Link List is not printing while using reverse iteration method -


i trying print link list in reverse order when run it's not printing out. stopping after printing correct order , output screen hangs after that. here's code:

#include<stdio.h> #include<conio.h> #include<stdlib.h> struct node{     int data;     struct node *next; }; void reverse(struct node*); void main() {     struct node *a;     char ch;     struct node *temp;     struct node *temp1;     a=null;     clrscr();         {     if(a==null)     {         temp=(struct node*)malloc(sizeof(struct node));         printf("enter data");         scanf("%d",&temp->data);         temp->next=null;         a=temp;     }        else     {     temp=(struct node*)malloc(sizeof(struct node));     temp->next=null;     printf("enter data element");     scanf("%d",&temp->data);     temp1=a;     while(temp1->next!=null)         {         temp1=temp1->next;         }     temp1->next=temp;     }     printf("do wish continue");     ch=getch();     }     while(ch=='y'||ch=='y');     printf("status of link list");     temp1=a;     while(temp1!=null)     {     printf("%d ",temp1->data);     temp1=temp1->next;     }     reverse(a);     getch(); } void reverse(struct node *head) { struct node *prev,*current,*next,*t; current=head; prev=null; while(current!=null)     {     next=current;     current->next=prev;     prev=current;     current=next;     } head=prev; printf("displaying in reverse order"); t=head; while(t!=null)     {     printf("%d",t->data);     t=t->next;     }  } 

thanks!

you have 2 problems code.

1) next=current; should next=current->next; pointed out @bluepixy in comment

2) after calling reverse have lost list, i.e. head in main no longer pointing head of list. fix do:

struct node* reverse(struct node *head) {     ....     return head; } 

and in main

head = reverse(head); 

another solution is:

void reverse(struct node **head) { ... }                           ^                           notice  // called main as: reverse(&head); 

and dereference head before use in function. make changes *head in function change head in main.

btw: don't cast value returned malloc


Comments

Popular posts from this blog

mysql - Dreamhost PyCharm Django Python 3 Launching a Site -

java - Sending SMS with SMSLib and Web Services -

java - How to resolve The method toString() in the type Object is not applicable for the arguments (InputStream) -