Reverse a Doubly Linked List | Set-2 - GeeksforGeeks

08 Feb, 2022
Write a program to reverse the given Doubly Linked List.
See below diagrams for example.
          (a) Original Doubly Linked List  
          (b) Reversed Doubly Linked List  
Approach: In the previous post, doubly linked list is being reversed by swapping prev and next pointers for all nodes, changing prev of the head (or start) and then changing the head pointer in the end. In this post, we create a push function that adds the given node at the beginning of the given list. We traverse the original list and one by one pass the current node pointer to the push function. This process will reverse the list. Finally return the new head of this reversed list.
C++
Java
Python3
C#
Javascript
// C++ implementation to reverse// a doubly linked list#include <bits/stdc++.h> using namespace std; // a node of the doubly linked liststruct Node {    int data;    Node *next, *prev;}; // function to get a new nodeNode* getNode(int data){    // allocate space    Node* new_node = (Node*)malloc(sizeof(Node));     // put in the data    new_node->data = data;    new_node->next = new_node->prev = NULL;    return new_node;} // function to insert a node at the beginning// of the Doubly Linked Listvoid push(Node** head_ref, Node* new_node){    // since we are adding at the beginning,    // prev is always NULL    new_node->prev = NULL;     // link the old list off the new node    new_node->next = (*head_ref);     // change prev of head node to new node    if ((*head_ref) != NULL)        (*head_ref)->prev = new_node;     // move the head to point to the new node    (*head_ref) = new_node;} // function to reverse a doubly linked listvoid reverseList(Node** head_ref){    // if list is empty or it contains    // a single node only    if (!(*head_ref) || !((*head_ref)->next))        return;     Node* new_head = NULL;    Node *curr = *head_ref, *next;     while (curr != NULL) {         // get pointer to next node        next = curr->next;         // push 'curr' node at the beginning of the        // list with starting with 'new_head'        push(&new_head, curr);         // update 'curr'        curr = next;    }     // update 'head_ref'    *head_ref = new_head;} // Function to print nodes in a// given doubly linked listvoid printList(Node* head){    while (head != NULL) {        cout << head->data << " ";        head = head->next;    }} // Driver program to test aboveint main(){    // Start with the empty list    Node* head = NULL;     // Create doubly linked: 10<->8<->4<->2 */    push(&head, getNode(2));    push(&head, getNode(4));    push(&head, getNode(8));    push(&head, getNode(10));     cout << "Original list: ";    printList(head);     // Reverse doubly linked list    reverseList(&head);     cout << "\nReversed list: ";    printList(head);     return 0;}
// Java implementation to reverse// a doubly linked listclass GFG{ // a node of the doubly linked liststatic class Node{    int data;    Node next, prev;}; // function to get a new nodestatic Node getNode(int data){    // allocate space    Node new_node = new Node();     // put in the data    new_node.data = data;    new_node.next = new_node.prev = null;    return new_node;} // function to insert a node at the beginning// of the Doubly Linked Liststatic Node push(Node head_ref, Node new_node){    // since we are adding at the beginning,    // prev is always null    new_node.prev = null;     // link the old list off the new node    new_node.next = (head_ref);     // change prev of head node to new node    if ((head_ref) != null)        (head_ref).prev = new_node;     // move the head to point to the new node    (head_ref) = new_node;         return head_ref;} // function to reverse a doubly linked liststatic Node reverseList(Node head_ref){    // if list is empty or it contains    // a single node only    if ((head_ref) == null || ((head_ref).next) == null)        return null;     Node new_head = null;    Node curr = head_ref, next;     while (curr != null)    {         // get pointer to next node        next = curr.next;         // push 'curr' node at the beginning of the        // list with starting with 'new_head'        new_head = push(new_head, curr);         // update 'curr'        curr = next;    }     // update 'head_ref'    head_ref = new_head;         return head_ref;} // Function to print nodes in a// given doubly linked liststatic void printList(Node head){    while (head != null)    {        System.out.print(head.data + " ");        head = head.next;    }} // Driver program to test abovepublic static void main(String args[]){    // Start with the empty list    Node head = null;     // Create doubly linked: 10< - >8< - >4< - >2 /    head = push(head, getNode(2));    head = push(head, getNode(4));    head = push(head, getNode(8));    head = push(head, getNode(10));     System.out.print("Original list: ");    printList(head);     // Reverse doubly linked list    head = reverseList(head);     System.out.print("\nReversed list: ");    printList(head);}} // This code is contributed by Arnab Kundu
# Python3 implementation to reverse# a doubly linked listimport math # a node of the doubly linked listclass Node:    def __init__(self, data):        self.data = data        self.next = None # function to get a new nodedef getNode(data):         # allocate space    new_node = Node(data)     # put in the data    new_node.data = data    new_node.next = None    new_node.prev = None    return new_node # function to insert a node at the beginning# of the Doubly Linked Listdef push(head_ref, new_node):         # since we are adding at the beginning,    # prev is always None    new_node.prev = None     # link the old list off the new node    new_node.next = head_ref     # change prev of head node to new node    if (head_ref != None):        head_ref.prev = new_node     # move the head to point to the new node    head_ref = new_node    return head_ref # function to reverse a doubly linked listdef reverseList(head_ref):         # if list is empty or it contains    # a single node only    if (head_ref == None or       (head_ref).next == None):        return None     new_head = None    curr = head_ref     while (curr != None):         # get pointer to next node        next = curr.next         # push 'curr' node at the beginning of the        # list with starting with 'new_head'        new_head = push(new_head, curr)         # update 'curr'        curr = next         # update 'head_ref'    head_ref = new_head     return head_ref # Function to print  nodes in a# given doubly linked listdef printList(head):    while (head != None) :        print(head.data, end = " ")        head = head.next # Driver Codeif __name__=='__main__':         # Start with the empty list    head = None     # Create doubly linked: 10<.8<.4<.2 */    head = push(head, getNode(2));    head = push(head, getNode(4));    head = push(head, getNode(8));    head = push(head, getNode(10));     print("Original list: ", end = "")    printList(head)     # Reverse doubly linked list    head = reverseList(head)     print("\nReversed list: ", end = "")    printList(head) # This code is contributed by Srathore
// C# implementation to reverse// a doubly linked listusing System; class GFG{ // a node of the doubly linked listpublic class Node{    public int data;    public Node next, prev;}; // function to get a new nodestatic Node getNode(int data){    // allocate space    Node new_node = new Node();     // put in the data    new_node.data = data;    new_node.next = new_node.prev = null;    return new_node;} // function to insert a node at the beginning// of the Doubly Linked Liststatic Node push(Node head_ref, Node new_node){    // since we are adding at the beginning,    // prev is always null    new_node.prev = null;     // link the old list off the new node    new_node.next = (head_ref);     // change prev of head node to new node    if ((head_ref) != null)        (head_ref).prev = new_node;     // move the head to point to the new node    (head_ref) = new_node;         return head_ref;} // function to reverse a doubly linked liststatic Node reverseList(Node head_ref){    // if list is empty or it contains    // a single node only    if ((head_ref) == null || ((head_ref).next) == null)        return null;     Node new_head = null;    Node curr = head_ref, next;     while (curr != null)    {         // get pointer to next node        next = curr.next;         // push 'curr' node at the beginning of the        // list with starting with 'new_head'        new_head = push(new_head, curr);         // update 'curr'        curr = next;    }     // update 'head_ref'    head_ref = new_head;         return head_ref;} // Function to print nodes in a// given doubly linked liststatic void printList(Node head){    while (head != null)    {        Console.Write(head.data + " ");        head = head.next;    }} // Driver codepublic static void Main(String []args){    // Start with the empty list    Node head = null;     // Create doubly linked: 10< - >8< - >4< - >2 /    head = push(head, getNode(2));    head = push(head, getNode(4));    head = push(head, getNode(8));    head = push(head, getNode(10));     Console.Write("Original list: ");    printList(head);     // Reverse doubly linked list    head = reverseList(head);     Console.Write("\nReversed list: ");    printList(head);}} // This code has been contributed by 29AjayKumar
<script>// javascript implementation to reverse// a doubly linked list     // a node of the doubly linked listclass Node {    constructor() {        this.data = 0;        this.prev = null;        this.next = null;    }}    // function to get a new node    function getNode(data) {        // allocate spacevar new_node = new Node();         // put in the data        new_node.data = data;        new_node.next = new_node.prev = null;        return new_node;    }     // function to insert a node at the beginning    // of the Doubly Linked List    function push(head_ref,  new_node) {        // since we are adding at the beginning,        // prev is always null        new_node.prev = null;         // link the old list off the new node        new_node.next = (head_ref);         // change prev of head node to new node        if ((head_ref) != null)            (head_ref).prev = new_node;         // move the head to point to the new node        (head_ref) = new_node;         return head_ref;    }     // function to reverse a doubly linked list    function reverseList(head_ref) {        // if list is empty or it contains        // a single node only        if ((head_ref) == null || ((head_ref).next) == null)            return null; var new_head = null;var curr = head_ref, next;         while (curr != null) {             // get pointer to next node            next = curr.next;             // push 'curr' node at the beginning of the            // list with starting with 'new_head'            new_head = push(new_head, curr);             // update 'curr'            curr = next;        }         // update 'head_ref'        head_ref = new_head;         return head_ref;    }     // Function to print nodes in a    // given doubly linked list    function printList(head) {        while (head != null) {            document.write(head.data + " ");            head = head.next;        }    }     // Driver program to test above             // Start with the empty listvar head = null;         // Create doubly linked: 10< - >8< - >4< - >2 /        head = push(head, getNode(2));        head = push(head, getNode(4));        head = push(head, getNode(8));        head = push(head, getNode(10));         document.write("Original list: ");        printList(head);         // Reverse doubly linked list        head = reverseList(head);         document.write("<br/>Reversed list: ");        printList(head); // This code contributed by Rajput-Ji</script>
Output: 
Original list: 10 8 4 2
Reversed list: 2 4 8 10
Time Complexity: O(n). 
andrew1234
29AjayKumar
nidhi_biet
sapnasingh4991
Rajput-Ji
simranarora5sos
sweetyty
surindertarika1234
simmytarika5
doubly linked list
Reverse
Linked List
Linked List
Reverse
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
LinkedList in Java
Linked List vs Array
Doubly Linked List | Set 1 (Introduction and Insertion)
Merge two sorted linked lists
Detect loop in a linked list
Find the middle of a given linked list
Implement a stack using singly linked list
Queue - Linked List Implementation
Implementing a Linked List in Java using Class
Circular Linked List | Set 1 (Introduction and Applications)