Ali
Ali

Reputation: 5476

Changing a line in linked list reversal causes error

This question is probably one of the most popular questions around and while searching for a solution, I've found many but the code below was the most suitable for me.

What it actually does is that it creates another list and iterates through the old list and add the element always to the head of the new list.

Node *reverseList(Node *oldList)
{
    Node* newList=NULL;

    while(oldList!=NULL)
    {
        Node *temp=oldList;
        oldList=oldList->next;

        temp->next=newList;
        newList=temp;  
    }
    return newList;
}

However when I decided to re-implement this idea without looking at this code I've changed place of the oldList=oldList->next; and put it after the newList=temp.

My question is does it really make a difference? I couldn't comprehend the reason because after all you are iterating through the oldList. Why would it require to be done immediately after the *temp declaration?

Upvotes: 2

Views: 99

Answers (1)

Stuart Golodetz
Stuart Golodetz

Reputation: 20626

After doing

Node *temp = oldList;

both pointers point at the same place. Since

temp->next = newList;

will overwrite the next pointer of oldList (because it points to the same thing as temp at this stage), you need to update oldList from its next pointer first.

Upvotes: 2

Related Questions