I am trying to reverse a doubly linked list using iterative approach and i’m struck on the part where my original list is being modified even though i’m not using a pointer to pointer style modification of original list.
This is the reverse function i am using, head is a local variable declared in main
like Node* head = NULL; and is already populated with a set of values.
Node* reverse_iterative(Node* head)
{
if(head == NULL || head->next == NULL)
return head;
Node *prev, *current=head, *temp;
while(current != NULL)
{
current->prev = current->next;
current->next = temp;
temp = current;
current = current->prev;
}
return temp;
}
This is how i used this in main :
Node* rev = NULL;
rev = reverse_iterative(head);
Here is the output i got:
original list: 15 <=>25 <=>35 <=>45 <=>55 <=>65 <=>75 <=>
making the list actually reverse: 75 <=>65 <=>55 <=>45 <=>35 <=>25 <=>15 <=>
after reversing, the original list now: 15 <=>
I couldn’t get the part where my original head node was being modified.
Look carefully at your while-loop, and consider the following statement on the initial iteration of the loop:
What is in
tempat the time of this assignment? Exposing more of the code, we have:Note that temp is uninitialized and thus an undefined pointer value. Your original head-ptr next ptr is being reset to garbage held in the uninitialized temp.
Fix this by doing the following:
I’ve not had a chance to test it, but that should get you closer to what you’re looking for.