Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

# Reverse a Doubly Linked List

Last Updated on July 27, 2023 by Mayank Dham

x

Linked list is one of the most famous and important data structures asked in most interviews. In this article, we will learn how to reverse a doubly linked list

A doubly linked list is a data structure which contains nodes with points to the previous node as well to the next node.

## How to Reverse a Doubly Linked List

In this problem, we will be given a doubly linked list as input, and we need to reverse it such that the pointer currently pointing to the head of the list will point to the tail of the doubly linked list.

According to the problem statement, we will be given a doubly-linked list, and we need to reverse a doubly linked list.

Let’s understand this problem with the help of some examples.

If the given doubly linked list is:

• According to the problem statement we need to reverse this given doubly linked list such that after reversing the doubly linked list will look like:

Taking another example, if the given list is head -> 1 2 3 5 6 -> NULL.

• In this case after reversing a doubly linked list our list will look like: head -> 6 5 3 2 1 -> NULL.

Some more examples

Sample Input 1: 1 3 5 7 11 -> NULL.
Sample Output 1: 11 7 5 3 1 -> NULL.

Sample Input 2: 2 3 5 7 11 17 -> NULL.
Sample Output 2: 17 11 7 5 3 2 -> NULL.

Now, I think from the above examples, the problem statement is clear. Let’s see how we can approach it.

Before moving to the approach section, try to think about how you can reverse a doubly linked list.

• If stuck, no problem, we will thoroughly see how we can reverse a doubly linked list in the next section.

Let’s move to the approach section.

### Approach 1 : Using 2 Pointers

This approach will be similar to reversing data present in an array.
1) We will initialize 2 pointers, one at starting and the other at the end of the linked list.
2) We will swap the node’s data to which the pointers are pointing.
3) And then, we will move the pointers toward’s each other by one step.
4) We will be performing step 2 and step 3 untill both the pointers do not cross each other or reach at the same position.
5) Finally, when both pointers reaches the same position, our doubly linked list will be fully reversed.

Time Complexity: O(n), 2 traversals will be required in this approach, one to get the address of the last node and another traversal to reverse the list.

Space Complexity: O(1)

The above approach will work fine, but the only issue is that we are traversing the doubly linked list twice. Now we need to ask ourselves one simple question: Do we actually need two list traversals to reverse the doubly linked list.

Is it possible to reverse a doubly linked list in a single traversal?

• Yes, it is possible, and we will see it in the following approach.

Let’s move to next approach.

### Approach 2: Swapping

Because we can access both the previous and next node of a given node in a doubly linked list, we can easily achieve list reversal by swapping the previous and next pointers of all nodes iteratively.

Let’s move to the algorithm section to see the above approach in depth.

### Algorithm

• Create a pointer current. Initialize it with the head of the linked list.
• Create a pointer temp. Initialize it with NULL.
• Now swap current’s prev and current’s next using pointer temp.
• Now move current to current’s previous node because after swapping, current’s prev stores the address of current’s next node.
• Repeat the process till current does not become NULL.

### Code Implementation to Reverse a Doubly Linked List:

```#include <stdio.h>
#include <stdlib.h>

/* a node of the doubly linked list */
struct Node
{
int data;
struct Node *next;
struct Node *prev;
};

/* Function to reverse a Doubly Linked List */
{
struct Node *temp = NULL;

while (current !=  NULL)
{
temp = current->prev;
current->prev = current->next;
current->next = temp;
current = current->prev;
}

if(temp != NULL )
}

/* UTILITY FUNCTIONS */
/* Function to insert a node at the beginning of the Doubly Linked List */
void push(struct Node** head_ref, int new_data)
{
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));

new_node->data  = new_data;

new_node->prev = NULL;

}

/* Function to print nodes in a given doubly linked list
This function is same as printList() of singly linked list */
void printList(struct Node *node)
{
while(node!=NULL)
{
printf("%d ", node->data);
node = node->next;
}
}

int main()
{

printf("\n Initial linked list before reversing: ");

printf("\n Resultant reversed linked list: ");

getchar();
}
```
```
#include <bits/stdc++.h>
using namespace std;

/* Node structure of a doubly linked list node */
class Node
{
public:
int data;
Node* next;
Node* prev;
};

/* Using this below function we will be adding a new node at beginning of the list */
{

Node* new_node = new Node();

new_node->data = x;

new_node->prev = NULL;

}

/* Using this below function we will be printing the content of the linked list */
void print_list(Node* node)
{
while (node != NULL)
{
cout << node->data << ",";
node = node->next;
}
cout<<endl;
}

/* Using this below function we will be reversing the given doubly linked list */
{
Node *temp = NULL;

while (current != NULL)
{
temp = current->prev;
current->prev = current->next;
current->next = temp;
current = current->prev;
}

if(temp != NULL )
}

/* Main function */
int main()
{

cout<<"Initial linked list before reversing: "<<endl;

return 0;
}

```
```class DoublyLinkedList {

static class Node {

int data;
Node next, prev;

Node(int d)
{
data = d;
next = prev = null;
}
}

/* Function to reverse a Doubly Linked List */
void reverse_list()
{
Node temp = null;

/* swap next and prev for all nodes of
while (current != null) {
temp = current.prev;
current.prev = current.next;
current.next = temp;
current = current.prev;
}

/* Before changing head, check for the cases like
empty list and list with only one node */
if (temp != null) {
}
}
/* Function to insert a node at the beginning of the
{
Node new_node = new Node(new_data);

new_node.prev = null;

}
}
void print_list(Node node)
{
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
}

public static void main(String[] args)
{

list.reverse_list();
System.out.println("");
System.out.println("The reversed Linked List is ");
}
}

```
```
class Node:
# Node structure of a doubly linked list node
def __init__(self, data):
self.data = data
self.next = None
self.prev = None

def __init__(self):

# Function reverse a Doubly Linked List
def reverse_list(self):
temp = None

while current is not None:
temp = current.prev
current.prev = current.next
current.next = temp
current = current.prev

if temp is not None:

# Using this below function we will be adding a new node at beginning of the list

new_node = Node(x)

new_node.prev = None

# Using this below function we will be printing the content of the linked list
def print_list(self, node):
while(node is not None):
print(node.data,end=',')
node = node.next

# main code

print ("Initial linked list before reversing: ")

dll.reverse_list()

print ("Resultant reversed linked list: ")
```

#### Output

2,7,1,13,17,
17,13,1,7,2,

Time Complexity: O(n), where n is the number of nodes in the linked list.

Conclusion
Reversing a doubly linked list is an essential operation that involves reversing the direction of pointers in each node, resulting in a complete reversal of the list. We explored two approaches to achieve this task. The first approach, using two pointers, requires two traversals of the list to swap the nodes’ data. On the other hand, the second approach, which involves swapping the previous and next pointers of each node iteratively, accomplishes the reversal in a single pass. Both approaches have a time complexity of O(n), where n is the number of nodes in the linked list. However, the second approach, using swapping, is more efficient as it performs the reversal with only one traversal, reducing the overall time complexity. Reversing a doubly linked list is a crucial operation in linked list manipulation and is often used in various algorithms and data structure implementations. By understanding and applying these techniques, developers can efficiently reverse a doubly linked list and manipulate the data structure according to their specific needs.

Here are some of the frequently asked questions on how to reverse doubly linked list

Q1. What is a doubly linked list?
A doubly linked list is a data structure that contains nodes that point to both the previous and next node.

Q2. What is the time complexity for reversing a doubly linked list?
Reversing a doubly linked list has a time complexity of O(1).

Q3. Can we reverse a doubly linked list in less than O(N)?
Because we need to traverse to the end to find the tail node, we can reverse a doubly linked list in less than O(N) time.