# Reverse a Doubly Linked List by swapping data

• Difficulty Level : Easy
• Last Updated : 16 Dec, 2022

Given a Doubly Linked List, we are asked to reverse the list in place without using any extra space.

Examples:

Input : 1 <--> 2 <--> 5 <--> 6 <--> 7
Output : 7 <--> 6 <--> 5 <--> 2 <--> 1

Input : 11 <--> 22 <--> 33 <--> 22 <--> 1
Output : 1 <--> 22 <--> 33 <--> 22 <--> 11

We have discussed three methods to reverse a doubly-linked list: Reverse a doubly-linked list, Reverse a Doubly Linked List (Set 2) and Reverse a Doubly linked list using recursion.
The first two methods work in O(n) time and require no extra space. The first method works by swapping the next and previous pointers of each node. The second method takes each node from the list and adds it to the beginning of the list.
There is another approach that is a bit more intuitive, but also a bit more costly.
This method is similar to the reverse array. To reverse an array, we put two pointers-one at the beginning and another at the end of the list. We then swap the data of the two pointers and advance both pointers toward each other. We stop either when the two pointers meet or when they cross each other. We perform exactly n/2 swaps, and the time complexity is also O(N).
A doubly linked list has both a previous and a next pointer, which means we can traverse in both forward and backward directions in the list. So if we put a pointer( say left pointer) at the beginning of the list and another right pointer at the end of the list, we can move these pointers toward each other by advancing the left pointer and receding the right pointer.

Algorithm:

Step 1: Set LEFT to head of list
Step 2: Traverse the list and set RIGHT to end of the list
Step 3: Repeat following steps while LEFT != RIGHT and
LEFT->PREV != RIGHT
Step 4: Swap LEFT->DATA and RIGHT->DATA
Step 5: Advance LEFT pointer by one, LEFT = LEFT->NEXT
Step 6: Recede RIGHT pointer by one, i.e RIGHT = RIGHT->PREV
[END OF LOOP]
Step 7: End

A Note on the comparative efficiency of the three methods

A few things must be mentioned. This method is simple to implement, but it is also more costly when compared to the pointer-exchange method. This is because we swap data and not pointers. Swapping data can be more costly if the nodes are large complex data types with multiple data members. In contrast, the pointer to the node will always be a simpler data type and either 4 or 8 bytes.

Below is the implementation of the algorithm.

## Javascript



Output

1 <--> 2 <--> 3 <--> 4 <--> 5
List After Reversing
5 <--> 4 <--> 3 <--> 2 <--> 1

Time Complexity: O(n), as we are using a loop to traverse n times. Where n is the number of nodes in the linked list.
Auxiliary Space: O(1), as we are not using any extra space.

My Personal Notes arrow_drop_up
Related Articles