Why does linked list work for node name, but not the pointer?

101 Views Asked by At

I am writing the code for reversing a linked list. This is the code

Node* reverseLinkedList(Node *head)
{
    Node* temp = head;
    Node* prev = NULL;
    while(temp != nullptr) { 
        Node* next = temp->next;
        temp->next = prev;
        prev = temp;
        temp = next;
    }
    return prev;
}

And it works perfectly. However, since the next node is just temp->next, why can't I use

Node* reverseLinkedList(Node *head)
{
    Node* temp = head;
    Node* prev = NULL;
    while(temp != nullptr) { 
        Node* next = temp->next;
        temp->next = prev;
        prev = temp;
        temp = temp->next;
    }
    return prev;
}

The above now does not work. I would appreciate some clarity on how nodes are working here.Thanks!

3

There are 3 best solutions below

0
Sugar On BEST ANSWER

because the temp->next were overwritten earlier

Node* reverseLinkedList(Node *head)
{
    Node* temp = head;
    Node* prev = NULL;
    while(temp != nullptr) { 
        Node* next = temp->next;
        temp->next = prev; // <<< here you assign new value
        prev = temp;
        temp = temp->next; // <<< here you use new value
    }
    return prev;
}
0
paddy On

The two code examples are not equivalent.

In the first one, you store the current value of temp->next in the variable next. The reason you do this is that you're about to overwrite the value with temp->next = prev; on the very next line.

If you don't make a copy of that pointer, then you'll have no way of knowing what the next node in the original list is.

In the second example, you see exactly what happens if you forget that you modified the value. It is overwritten with prev, and then later on when you advance to the "next" node, you are actually advancing to prev, which is always NULL and your loop terminates.

So, technically, in the second example you do actually keep the original next but it's never used so that line is completely redundant and can be optimized away. The compiler should issue a warning that you have an unused variable, and this is often an indication of an accidental bug.

1
Rutik Parmar On

its not working because at the time when you do temp = temp->next the temp->next is pointing to prev.