The following is my reverse linked list code. It is running in endless loop(on the second node i.e it continuously prints 2-> if the list is 1->2->3->4). Any help will be appreciated.
first
is the head node pointer. Temp
is the temporary node. Prev
is the previous node.
The structure of the node is
struct node {
int num;
struct node *ptr;
} ;
The idea behind this approach is :- I will iteratively find the last node and print it. The prev node points to the node just before the temp node , which is the node that finally points to the last node before deleting it. The outer while loop terminates as soon as the first , which is the pointer to the first node of the list is the last node . Every time the else block of the outer while loop is executed. The prev and temp points to the next node after the first node.
The insertion of the linked list is working properly. I have already checked that part. I have also run through the entire code a couple of times and tried predicting each step but to no avail.
while (1)
{
if (first->ptr == 0)
{
printf("%d\n",first->num);
break;
}
else
{
temp = prev = first->ptr;
while (1)
{
if (temp->ptr == 0)
{
printf("%d->", temp->num);
temp = 0;
prev->ptr = 0;
break;
}
else
{
prev = temp->ptr;
prev = temp;
temp = temp->ptr;
}
}
}
}