1

I am not able to print the first node after reversing doubly linked list.

I have used structure to create nodes , I can tell that I am correctly swapping the prev and next pointers but it doesn't give the output as expected.

#include<bits/stdc++.h>
using namespace std;
struct Node {
    int data;
    Node *next;
    Node *prev;
    Node(int x) {
        data =x;
        next=NULL;
        prev=NULL;
    }
};
void traverse(Node *head)
{
    while(head!=NULL)
    {
        cout<<head->data<<" ";
        head=head->next;
    }
}

Reverse function to reverse the doubly linked list

Node *reverse(Node *head)
{
    if(head==NULL || head->next==NULL)
        return head;
    Node *prev = NULL;       // previous serve two purposes first it will help in swapping
    Node *curr = head;      //  and in the end it will help to locate the last node when current becomes null
    while(curr!=NULL)
    {
        cout<<"reversing a node\n";
        prev = curr->prev;
        curr->prev=curr->next;
        curr->next=prev;
        
        curr=curr->prev;
    }
    cout<<"yes";
    return prev;
}

insert begin function to add node in start of the linked list

Node *insertBegin(Node *head,int data)
{
    Node *tmp = new Node(data);
    tmp->next=head;
    if((head!=NULL))
        head->prev=tmp;
    return tmp;
}

int main()
{
//  Node *head = new Node(10);
//  head->next=new Node(20);
//  head->next->prev=head;
//  head->next->next =new Node(30);
//  head->next->next->prev=head->next->next;
    
    Node *head =NULL;
    head=insertBegin(head,10);
    head=insertBegin(head,20);
    head=insertBegin(head,30);
    traverse(head);
    //linked list before reverse 30 20 10
    head = reverse(head);
    traverse(head);
    //linked list after traverse as showing on output 20 30
    return 0;
}

1 Answer 1

0

You are returning the second node in the list instead of the first node. You are returning the most recent good value of curr->prev when you should be returning the most recent good value of curr (which will be the head of the reversed list).

The minimal code change is probably:

return prev->prev;

Sign up to request clarification or add additional context in comments.

1 Comment

Oh thanks I forgot that prev will not be moved ahead when curr becomes null as while loop will not run to update prev's value and we will have to manually increment the prev pointer by prev = prev->prev , it would be better if I declared the prev with something else like behindCurr as I might have confused it with the prev pointer of nodes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.