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