Home > Enterprise >  how can I reverse my Linked list . I wrote following code but this is giving only first node's
how can I reverse my Linked list . I wrote following code but this is giving only first node's

Time:12-29

Node *reverse(Node *head)
{
    Node *answer = NULL, *p = head, *address = NULL;

    while (p != NULL)
    {
        address = p;
        address->next = answer;
        answer = address;
        p = p->next;
    }
    return answer;
}

CodePudding user response:

In order to reverse a singly linked list, you need to keep one node in memory to be able to relink backwards.

It could look like this:

Node* reverse(Node* head) {
    if(head) {                               // must have at least one node
        Node* curr = head->next;             // head   1
        head->next = nullptr;                // this will be the new last node
        Node* next;                          // for saving next while relinking
        while(curr) {                        // while curr != nullptr
            next = curr->next;               // save the next pointer
            curr->next = head;               // relink backwards
            head = curr;                     // move head forward
            curr = next;                     // move curr forward
        }
        // head now points at the new start of the list automatically
    }
    return head;
}

Demo

CodePudding user response:

I wrote following code but this is giving only first node's data as output

Because, in reverse() function, you are breaking the link of first node from rest of the list and returning it.

Look at this part of code:

        address = p;
        address->next = answer;
        answer = address;
        p = p->next;

In first iteration of while loop this is what happening:

Pointer address will point to head of list (as p is initialised with head) and, in the next statement, you are doing address->next = answer (note that answer is initialised with NULL). So, address->next is assigned NULL. Both, pointer p and pointer address are still pointing same node. After this, you are doing p = p->next, this will assign NULL to p because p->next is NULL. As, p is NULL, the while loop condition results in false and loop exits and function end up returning the first node.

You should assign p to its next before assigning answer to address->next, like this:

    while (p != NULL)
    {
        address = p;
        p = p->next;   // moved up
        address->next = answer;
        answer = address;
    }

Suggestion:

In C , you should use nullptr instead of NULL.

  • Related