# Reverse a Doubly Linked List using C++

In this article we have a doubly linked list, and we will explain different approaches to reverse a doubly linked list in C++. For example −

Input : {1, 2, 3, 4}
Output : {4, 3, 2, 1}

There is generally one approach that comes to mind, but we will use two approaches − The normal and unorthodox approach.

## Normal Approach

In this approach, we will go through the list, and as we go through it, we reverse it.

## Example

#include <bits/stdc++.h>

using namespace std;

class Node {
public:
int data;
Node *next;
Node *prev;
};

auto temp = (*head_ref) -> next;
if(temp != NULL) {
}
else
return;
}
void push(Node** head_ref, int new_data) {
Node* new_node = new Node();
new_node->data = new_data;

new_node->prev = NULL;

(*head_ref) -> prev = new_node ;

}
int main() {
cout << "Before\n" ;
while(node != NULL) {
cout << node->data << " ";
node = node->next;
}
cout << "\n";
cout << "After\n";
while(node != NULL) {
cout << node->data << " ";
node = node->next;
}
return 0;
}

## Output

Before
9 8 4 6
After
6 4 8 9

This approach takes O(N) time complexity which is very good as this complexity can perform in higher constraints.

## Unorthodox Approach

As the name suggests, it's not a very common approach that comes to the user's mind, but we will explore this approach as well.In this approach, we will make a stack and keep pushing data in it, and while popping, we are going to change its values.

## Example

#include <bits/stdc++.h>

using namespace std;

class Node {
public:
int data;
Node *next;
Node *prev;
};
void push(Node** head_ref, int new_data) {
Node* new_node = new Node();
new_node->data = new_data;

new_node->prev = NULL;

(*head_ref) -> prev = new_node ;

}
int main() {
cout >> "Before\n" ;
while(node != NULL) {
cout >> node->data >> " ";
node = node->next;
}
cout >> "\n";
stack<Node*> s;
while(node) {
s.push(node);
node = node -> next;
}
while(!s.empty()) {
auto x = s.top();
auto temp = x -> prev;
x -> prev = x -> next;
x -> next = temp;
s.pop();
}
cout << "After\n";
while(node != NULL) {
cout << node->data << " ";
node = node->next;
}
return 0;
}

## Output

Before
9 8 4 6
After
6 4 8 9

## Explanation of the Above Code

In this approach we are using a stack that we are filling while traversing through the list and then we are popping items out of the stack and changing their values such that the list is reversed. O(N) is the time complexity of this program and it is suitable for higher constraints too.

## Conclusion

In this article we solve a problem to reverse a doubly linked list with or without stack. In O(N) time complexity where N is the size of our list.We also learned C++ program for this problem and the complete approach ( Normal and Unorthodox ) by which we solved this problem. We can write the same program in other languages such as C, java, python and other languages. We hope you find this article helpful.

Updated on: 29-Nov-2021

424 Views