Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is temporary Node necessary in Reversing a linked list in cpp?

Here is the working code:

Node* Reverse(Node *head)
{
    Node *prev = NULL;
    Node *next;
    Node *current = head;
    while (current != NULL)
    {
        next = current -> next;
        current -> next = prev;
        prev = current;
        current = next;
    }
    head = prev;

    return head;
}

And this doesn’t work when I remove the temporary variable current.

Node* Reverse(Node *head)
{
    Node *prev = NULL;
    // Node *current = head;
    Node *next;
    while (head != NULL)
    {
        next = head -> next;
        head -> next = prev;
        prev = head;
        head = next;
    }
    return head;
}

I understand that we need next since we have to keep track of it before losing access to it. But I cannot think of why the temporary variable current is necessary? Any help would be appreciated.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You don’t need the current variable. (despite it’s name head would be confusing)


The code is different because you don’t assign prev to head in the second snippet.

Node* Reverse(Node *head)
{
    Node *prev = NULL;
    // Node *current = head;
    Node *next;
    while (head != NULL)
    {
        next = head -> next;
        head -> next = prev;
        prev = head;
        head = next;
    }
    
    // or head=prev; return head;
    return prev; // <--- 
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading