简体   繁体   中英

How to reverse doubly Linked list?

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;
}

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM