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

Time:04-05

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.

CodePudding user response:

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; // <--- 
}
  • Related