Home > Software design >  How to reverse doubly Linked list?
How to reverse doubly Linked list?

Time:08-22

Can anyone help me with it? Why it is showing runtime error

Node* rev(Node*head)
{
    if(head==NULL || head->next==NULL)
    {
        return head;
    }

    Node * chotahead =rev(head->next);
    head->next->next=head;
    head->prev=head->next;
    head->next=NULL;
    return chotahead;
}


Node* reverseDLL(Node * head)
{

    head=rev(head);
    return head;
}

CodePudding user response:

How about something like this:

void Reverse_List(list * p_list)
{
    Node * p->head = p_list->p_head;
    Node * p_new_head = p_list->p_head;
    while (p->head)
    {
       p_temp = p_head->next;
       p_head->next = p_new_head;
       p_new_head = p_head;
       p_head = temp;
    }
    list->p_head = p_new_head;
}

The idea with the above code is that you start with an new empty list. Traverse the existing list, and move the nodes to the head of the new list.

Lastly, make the head of the list point to the new list.

Note: the above code doesn't use recursion and has minimal effect to the stack.

CodePudding user response:

Every iteration sets next node's next pointer and current node's prev pointer. That leaves last node's prev pointer and first node's next pointer unset. Fixing that makes the code work.

[Demo]

Node* rev(Node* head) {
    if (head->next == nullptr) {
        head->prev = nullptr;  // last node's prev
        return head;
    }

    Node* chotahead = rev(head->next);
    head->next->next = head;  // next node's next
    head->prev = head->next;  // current node's prev
    return chotahead;
}

Node* reverseDLL(Node* head) {
    if (head == nullptr) {
        return head;
    }
    Node* ret = rev(head);
    head->next = nullptr;  // first node's next
    return ret;
}

The code could be simplified though:

  • No need for two functions.
  • No need for recursivity.
  • You can walk the original list, exchanging next and prev pointers, and returning the current node when it is the last one.

[Demo]

Node* reverse(Node* head) {
    Node* ret{nullptr};
    while (head != nullptr) {
        ret = head;
        head = std::exchange(head->next, head->prev);
    }
    return ret;
}
  • Related