Reputation: 33
I am trying to print the link list in reverse order but when I run it it's not printing it out. It is just stopping after printing the correct order and the output screen hangs after that. Here's my 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();
do
{
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 You Wish to continue");
ch=getch();
}
while(ch=='Y'||ch=='y');
printf("Status of the 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!
Upvotes: 1
Views: 62
Reputation: 44274
You have two problems with the code.
1) next=current;
should be next=current->next;
as pointed out by @BLUEPIXY in a comment
2) After calling reverse
you have lost your list, i.e. head
in main is no longer pointing to head of the list. To fix this you could 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 from main as: reverse(&head);
and then dereference head
before use in the function. This will make changes to *head
in the function to change head
in main
.
BTW: Don't cast the value returned by malloc
Upvotes: 4