[Naive Approach] Using Recursion - O(n) Time and O(n) Space
The idea of the recursive code is simple,
Swap the next and previous pointers (or references) of the current node.
Recursively call for the remaining list (We mainly need to call for curr->prev as previous now hold the earlier next node).
C++
// C++ program to reverse a//doubly linked list using recursion#include<iostream>usingnamespacestd;classNode{public:intdata;Node*next,*prev;Node(intval){data=val;next=nullptr;prev=nullptr;}};// Recursive function to reverse a doubly linked listNode*reverse(Node*curr){// Base case: if the list is empty or we// reach the end of the listif(curr==nullptr)returnnullptr;// Swap the next and prev pointersswap(curr->prev,curr->next);// If the previous node (after swap) is null,// this is the new headif(curr->prev==nullptr)returncurr;// Recurse for the next nodereturnreverse(curr->prev);}voidprintList(Node*node){while(node!=nullptr){cout<<node->data<<" ";node=node->next;}}intmain(){// Create a hard-coded doubly linked list:// 1 <-> 2 <-> 3 <-> 4Node*head=newNode(1);head->next=newNode(2);head->next->prev=head;head->next->next=newNode(3);head->next->next->prev=head->next;head->next->next->next=newNode(4);head->next->next->next->prev=head->next->next;cout<<"Original Linked list"<<endl;printList(head);head=reverse(head);cout<<"\nReversed Linked list"<<endl;printList(head);return0;}
C
// C program to reverse a doubly//linked list using recursion#include<stdio.h>structNode{intdata;structNode*next;structNode*prev;};// Recursive function to reverse a doubly linked list structNode*reverse(structNode*curr){// Base case: If the list is empty or we// reach the end of the listif(curr==NULL)returnNULL;// Swap the next and prev pointersstructNode*temp=curr->prev;curr->prev=curr->next;curr->next=temp;// If the previous node (after swap) is NULL// his is the new headif(curr->prev==NULL)returncurr;// Recurse for the next node returnreverse(curr->prev);}voidprintList(structNode*node){while(node!=NULL){printf("%d ",node->data);node=node->next;}printf("\n");}structNode*createNode(intnew_data){structNode*new_node=(structNode*)malloc(sizeof(structNode));new_node->data=new_data;new_node->next=NULL;new_node->prev=NULL;returnnew_node;}intmain(){// Create a hrad-coded doubly linked list:// 1 <-> 2 <-> 3 <-> 4structNode*head=createNode(1);head->next=createNode(2);head->next->prev=head;head->next->next=createNode(3);head->next->next->prev=head->next;head->next->next->next=createNode(4);head->next->next->next->prev=head->next->next;printf("Original Linked list\n");printList(head);head=reverse(head);printf("Reversed Linked list\n");printList(head);return0;}
Java
// Java program to reverse a// doubly linked list using recursionclassGfG{staticNodehead;staticclassNode{intdata;Nodenext,prev;Node(intd){data=d;next=prev=null;}}// Recursive function to reverse a doubly linked liststaticNodereverse(Nodecurr){// Base case: If list is empty or we // reach the end of the listif(curr==null)returnnull;// Swap the next and prev pointersNodetemp=curr.prev;curr.prev=curr.next;curr.next=temp;// If prev is null after swap, this is the new headif(curr.prev==null){returncurr;}// Recurse for the next nodereturnreverse(curr.prev);}staticvoidprintList(Nodenode){while(node!=null){System.out.print(node.data+" ");node=node.next;}System.out.println();}publicstaticvoidmain(String[]args){// Manually create a doubly linked list:// 1 <-> 2 <-> 3 <-> 4head=newNode(1);head.next=newNode(2);head.next.prev=head;head.next.next=newNode(3);head.next.next.prev=head.next;head.next.next.next=newNode(4);head.next.next.next.prev=head.next.next;System.out.println("Original linked list:");printList(head);// Reverse the doubly linked listhead=reverse(head);System.out.println("Reversed linked list:");printList(head);}}
Python
# Python program to reverse a doubly# linked list using recursionclassNode:def__init__(self,val):self.data=valself.next=Noneself.prev=None# Recursive function to reverse a doubly linked listdefreverse(curr):# Base case: if the list is empty or we reach the end of the listifcurrisNone:returnNone# Swap the next and prev pointerstemp=curr.prevcurr.prev=curr.nextcurr.next=temp# If the previous node (after swap) is null, this is the new headifcurr.previsNone:returncurr# Recurse for the next nodereturnreverse(curr.prev)defprint_list(node):whilenodeisnotNone:print(node.data,end=" ")node=node.nextprint()if__name__=="__main__":# Create a hard-coded doubly linked list:# 1 <-> 2 <-> 3 <-> 4head=Node(1)head.next=Node(2)head.next.prev=headhead.next.next=Node(3)head.next.next.prev=head.nexthead.next.next.next=Node(4)head.next.next.next.prev=head.next.nextprint("Original Linked list")print_list(head)head=reverse(head)print("\nReversed Linked list")print_list(head)
C#
// C# program to reverse a doubly// linked list using recursionusingSystem;publicclassNode{publicintData;publicNodeNext;publicNodePrev;publicNode(intval){Data=val;Next=null;Prev=null;}}classGfG{// Recursive function to reverse a doubly linked liststaticNodeReverse(Nodecurr){// Base case: if the list is empty or we reach the// end of the listif(curr==null)returnnull;// Swap the next and prev pointersNodetemp=curr.Prev;curr.Prev=curr.Next;curr.Next=temp;// If the previous node (after swap) is null, // this is the new headif(curr.Prev==null)returncurr;// Recurse for the next nodereturnReverse(curr.Prev);}// Function to print the linked liststaticvoidPrintList(Nodenode){while(node!=null){Console.Write(node.Data+" ");node=node.Next;}Console.WriteLine();}staticvoidMain(){// Create a hard-coded doubly linked list:// 1 <-> 2 <-> 3 <-> 4Nodehead=newNode(1);head.Next=newNode(2);head.Next.Prev=head;head.Next.Next=newNode(3);head.Next.Next.Prev=head.Next;head.Next.Next.Next=newNode(4);head.Next.Next.Next.Prev=head.Next.Next;Console.WriteLine("Original Linked list");PrintList(head);head=Reverse(head);Console.WriteLine("Reversed Linked list");PrintList(head);}}
JavaScript
// Javascript program to reverse a doubly// linked list using recursionclassNode{constructor(val){this.data=val;this.next=null;this.prev=null;}}// Recursive function to reverse a doubly linked listfunctionreverse(curr){// Base case: if the list is empty or we reach the end of the listif(curr===null){returnnull;}// Swap the next and prev pointersconsttemp=curr.prev;curr.prev=curr.next;curr.next=temp;// If the previous node (after swap) is null, this is the new headif(curr.prev===null){returncurr;}// Recurse for the next nodereturnreverse(curr.prev);}// Function to print the linked listfunctionprintList(node){letoutput='';while(node!==null){output+=node.data+' ';node=node.next;}console.log(output.trim());}// Create a hard-coded doubly linked list:// 1 <-> 2 <-> 3 <-> 4consthead=newNode(1);head.next=newNode(2);head.next.prev=head;head.next.next=newNode(3);head.next.next.prev=head.next;head.next.next.next=newNode(4);head.next.next.next.prev=head.next.next;console.log("Original Linked list:");printList(head);constreversedHead=reverse(head);console.log("\nReversed Linked list:");printList(reversedHead);
Output
Original Linked list
1 2 3 4
Reversed Linked list
4 3 2 1
Time Complexity: O(n), where n are the number of nodes in doubly linked list. Auxiliary Space: O(n)
[Expected Approach] Using Two Pointers - O(n) Time and O(1) Space
The idea is to reverse doubly linked listusing two pointers for traversing through the list and swapping the next and previous pointers of every two consecutive nodes.
Step-by-step algorithm:
Initially, prevNode is set to NULL and currNode starts at the head.
As the list is traversed,
Swap the currNode->next and currNode->prev
Move currNode to the next node, currNode = currNode->prev.
After traversing all the nodes, prevNode will point to the second node of the reversed list, so update the previous pointer of prevNode as the new head of the linked list, head = prevNode->prev and return it.
Working of the above algorithm:
Below is the implementation of the above approach:
C++
// C++ code to Reverse a doubly linked list,// using two pointers#include<iostream>usingnamespacestd;classNode{public:intdata;Node*next;Node*prev;Node(intnew_data){data=new_data;next=NULL;prev=NULL;}};// Function to reverse a doubly linked listNode*reverse(Node*head){// If the list is empty or has only one node,// return the head as isif(head==nullptr||head->next==nullptr)returnhead;Node*prevNode=NULL;Node*currNode=head;// Traverse the list and reverse the linkswhile(currNode!=nullptr){// Swap the next and prev pointersprevNode=currNode->prev;currNode->prev=currNode->next;currNode->next=prevNode;// Move to the next node in the original list // (which is now previous due to reversal)currNode=currNode->prev;}// The final node in the original list// becomes the new head after reversalreturnprevNode->prev;}voidprintList(Node*node){while(node!=nullptr){cout<<node->data<<" ";node=node->next;}cout<<endl;}intmain(){// Create a doubly linked list: // 1 <-> 2 <-> 3 <-> 4Node*head=newNode(1);head->next=newNode(2);head->next->prev=head;head->next->next=newNode(3);head->next->next->prev=head->next;head->next->next->next=newNode(4);head->next->next->next->prev=head->next->next;cout<<"Original Doubly Linked List"<<endl;printList(head);head=reverse(head);cout<<"Reversed Doubly Linked List"<<endl;printList(head);return0;}
C
// C code to Reverse a doubly linked list,// using two pointers#include<stdio.h>structNode{intdata;structNode*next;structNode*prev;};// Function to reverse a Doubly Linked List using two pointersstructNode*reverse(structNode*head){if(head==NULL||head->next==NULL)returnhead;structNode*prevNode=NULL;structNode*currNode=head;// Traverse the list and reverse the linkswhile(currNode!=NULL){// Swap the next and prev pointersprevNode=currNode->prev;currNode->prev=currNode->next;currNode->next=prevNode;// Move to the next node in the original list // (which is now previous due to reversal)currNode=currNode->prev;}// The final node processed will be the new head// Fix head pointerif(prevNode!=NULL)head=prevNode->prev;returnhead;}voidprintList(structNode*node){while(node!=NULL){printf("%d ",node->data);node=node->next;}printf("\n");}structNode*createNode(intnew_data){structNode*new_node=(structNode*)malloc(sizeof(structNode));new_node->data=new_data;new_node->next=NULL;new_node->prev=NULL;returnnew_node;}intmain(){// Create a hard-coded doubly linked list: // 1 <-> 2 <-> 3 <-> 4structNode*head=createNode(1);head->next=createNode(2);head->next->prev=head;head->next->next=createNode(3);head->next->next->prev=head->next;head->next->next->next=createNode(4);head->next->next->next->prev=head->next->next;printf("Original Doubly Linked List\n");printList(head);head=reverse(head);printf("Reversed Doubly Linked List\n");printList(head);return0;}
Java
// Java code to Reverse a doubly linked list,// using two pointersclassNode{intdata;Nodenext;Nodeprev;Node(intdata){this.data=data;this.next=null;this.prev=null;}}publicclassGfG{// Function to reverse a Doubly Linked List using two// pointersstaticNodereverse(Nodehead){if(head==null||head.next==null){returnhead;}NodecurrNode=head;NodeprevNode=null;// Traverse the list and reverse the linkswhile(currNode!=null){// Swap the next and prev pointersprevNode=currNode.prev;currNode.prev=currNode.next;currNode.next=prevNode;// Move to the next node in the original list// (which is now previous due to reversal)currNode=currNode.prev;}// Update head of Doubly Linked Listhead=prevNode.prev;returnhead;}staticvoidprintList(Nodenode){while(node!=null){System.out.print(node.data+" ");node=node.next;}System.out.println();}publicstaticvoidmain(String[]args){// Create a doubly linked list:// 1 <-> 2 <-> 3 <-> 4Nodehead=newNode(1);head.next=newNode(2);head.next.prev=head;head.next.next=newNode(3);head.next.next.prev=head.next;head.next.next.next=newNode(4);head.next.next.next.prev=head.next.next;System.out.println("Original Doubly Linked List");printList(head);head=reverse(head);System.out.println("Reversed Doubly Linked List");printList(head);}}
Python
# Python code to Reverse a doubly linked list,# using two pointersclassNode:def__init__(self,new_data):self.data=new_dataself.next=Noneself.prev=Nonedefreverse(head):# If the list is empty or has only one node,# return the head as isifheadisNoneorhead.nextisNone:returnheadprevNode=NonecurrNode=head# Traverse the list and reverse the linkswhilecurrNodeisnotNone:# Swap the next and prev pointersprevNode=currNode.prevcurrNode.prev=currNode.nextcurrNode.next=prevNode# Move to the next node in the original list# (which is now previous due to reversal)currNode=currNode.prev# The final node in the original list# becomes the new head after reversalreturnprevNode.prevdefprintList(node):whilenodeisnotNone:print(node.data,end=" ")node=node.nextprint()if__name__=="__main__":# Create a doubly linked list:# 1 <-> 2 <-> 3 <-> 4head=Node(1)head.next=Node(2)head.next.prev=headhead.next.next=Node(3)head.next.next.prev=head.nexthead.next.next.next=Node(4)head.next.next.next.prev=head.next.nextprint("Original Doubly Linked List")printList(head)head=reverse(head)print("Reversed Doubly Linked List")printList(head)
C#
// C# code to Reverse a doubly linked list,// using two pointersusingSystem;classNode{publicintData;publicNodeNext;publicNodePrev;publicNode(intnewData){Data=newData;Next=null;Prev=null;}}classGfG{// Function to reverse a doubly linked liststaticNodeReverse(Nodehead){// If the list is empty or has only one node,// return the head as isif(head==null||head.Next==null)returnhead;NodeprevNode=null;NodecurrNode=head;// Traverse the list and reverse the linkswhile(currNode!=null){// Swap the next and prev pointersprevNode=currNode.Prev;currNode.Prev=currNode.Next;currNode.Next=prevNode;// Move to the next node in the original list// (which is now previous due to reversal)currNode=currNode.Prev;}// The final node in the original list// becomes the new head after reversalreturnprevNode.Prev;}staticvoidPrintList(Nodenode){while(node!=null){Console.Write(node.Data+" ");node=node.Next;}Console.WriteLine();}publicstaticvoidMain(){// Create a doubly linked list: // 1 <-> 2 <-> 3 <-> 4Nodehead=newNode(1);head.Next=newNode(2);head.Next.Prev=head;head.Next.Next=newNode(3);head.Next.Next.Prev=head.Next;head.Next.Next.Next=newNode(4);head.Next.Next.Next.Prev=head.Next.Next;Console.WriteLine("Original Doubly Linked List");PrintList(head);head=Reverse(head);Console.WriteLine("Reversed Doubly Linked List");PrintList(head);}}
JavaScript
// Javascript code to Reverse a doubly linked list,// using two pointersclassNode{constructor(new_data){this.data=new_data;this.next=null;this.prev=null;}}// Function to reverse a doubly linked listfunctionreverse(head){// If the list is empty or has only one node,// return the head as isif(head===null||head.next===null)returnhead;letprevNode=null;letcurrNode=head;// Traverse the list and reverse the linkswhile(currNode!==null){// Swap the next and prev pointersprevNode=currNode.prev;currNode.prev=currNode.next;currNode.next=prevNode;// Move to the next node in the original list // (which is now previous due to reversal)currNode=currNode.prev;}// The final node in the original list// becomes the new head after reversalreturnprevNode.prev;}functionprintList(node){letoutput="";while(node!==null){output+=node.data+" ";node=node.next;}console.log(output);}// Create a doubly linked list:// 1 <-> 2 <-> 3 <-> 4lethead=newNode(1);head.next=newNode(2);head.next.prev=head;head.next.next=newNode(3);head.next.next.prev=head.next;head.next.next.next=newNode(4);head.next.next.next.prev=head.next.next;console.log("Original Doubly Linked List");printList(head);head=reverse(head);console.log("Reversed Doubly Linked List");printList(head);
Output
Original Doubly Linked List
1 2 3 4
Reversed Doubly Linked List
4 3 2 1
Time Complexity:O(n), where n denotes the number of nodes in the doubly linked list. Auxiliary Space:O(1)
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.