Clockwise rotation of Doubly Linked List by N places - GeeksforGeeks

08 Jun, 2021
Given a doubly-linked list and an integer N, the task is to rotate the linked list clockwise by N nodes.Examples:  
Input: N = 2  
Output:  
 
 
Approach: To rotate the Doubly linked list first check whether the given N is greater than the length of the list or not. If N is greater than the size of the list then deduce it in the range of linked list size by taking modulo with the length of the list. After that subtract the value of N from the length of the list. Now the problem reduces to the counter-clockwise rotation of a doubly-linked list by N places.  
Change the next of the last node to point the Head node.  
Change the prev of the Head node to point the last node.  
Change the value of the Head_ref to be the next of the Nth node.  
Change the value of next of the Nth Node to be NULL.  
Finally, make the prev of Head node to point to NULL.  
Below is the implementation of the above approach: 
C++
Java
Python3
C#
Javascript
// C++ program to rotate a Doubly linked// list clock wise by N times#include <bits/stdc++.h>using namespace std; /* Link list node */struct Node {    char data;    struct Node* prev;    struct Node* next;}; // Utility function to find the size of// Doubly Linked Listint size(struct Node* head_ref){    struct Node* curr = head_ref;    int sz = 0;    while (curr != NULL) {        curr = curr->next;        sz++;    }    return sz;} /* Function to print linked list */void printList(struct Node* node){    while (node->next != NULL) {        cout << node->data << " "             << "<=>"             << " ";        node = node->next;    }    cout << node->data;} // Function to insert a node at the// beginning of the Doubly Linked Listvoid push(struct Node** head_ref, int new_data){    struct Node* new_node = new Node;    new_node->data = new_data;    new_node->prev = NULL;    new_node->next = (*head_ref);    if ((*head_ref) != NULL)        (*head_ref)->prev = new_node;    *head_ref = new_node;} // Function to rotate a doubly linked// list clockwise and update the headvoid rotate(struct Node** head_ref, int N, int sz){     /* If N is greater than the size of Doubly    Linked List, we have to deduce it in the range    of Doubly linked list size by taking modulo with the    length of the list.*/    N = N % sz;     /* We will update N by subtracting it's value length of    the list. After this the question will reduce to    counter clockwise rotation of linked list to N places*/    N = sz - N;     if (N == 0)        return;     struct Node* current = *head_ref;     // current will either point to Nth    // or NULL after this loop. Current    // will point to node 'b' in the    // above example    int count = 1;    while (count < N && current != NULL) {        current = current->next;        count++;    }     // If current is NULL, N is greater    // than or equal to count of nodes    // in linked list    // Don't change the list in this case    if (current == NULL)        return;     // current points to Nth node. Store    // it in a variable. NthNode points to    // node 'b' in the above example    struct Node* NthNode = current;     // current will point to last node    // after this loop current will point    // to node 'e' in the above example    while (current->next != NULL)        current = current->next;     // Change next of last node to previous    // head. Next of 'e' is now changed to    // node 'a'    current->next = *head_ref;     // Change prev of Head node to current    // Prev of 'a' is now changed to node 'e'    (*head_ref)->prev = current;     // Change head to (N+1)th node    // head is now changed to node 'c'    *head_ref = NthNode->next;     // Change prev of New Head node to NULL    // Because Prev of Head Node in Doubly    // linked list is NULL    (*head_ref)->prev = NULL;     // Change next of Nth node to NULL    // next of 'b' is now NULL    NthNode->next = NULL;} // Driver codeint main(void){    /* Start with the empty list */    struct Node* head = NULL;     /* Create the doubly linked    list a<->b<->c<->d<->e */    push(&head, 'e');    push(&head, 'd');    push(&head, 'c');    push(&head, 'b');    push(&head, 'a');     int N = 2;     // Length of the list    int sz = size(head);     cout << "Given Doubly linked list \n";    printList(head);    rotate(&head, N, sz);     cout << "\nRotated Linked list clockwise \n";    printList(head);     return 0;}
// Java program to rotate a Doubly linked// list clock wise by N timesclass GFG{ /* Link list node */static class Node{    char data;    Node prev;    Node next;}; // Utility function to find the size of// Doubly Linked Liststatic int size(Node head_ref){    Node curr = head_ref;    int sz = 0;    while (curr != null)    {        curr = curr.next;        sz++;    }    return sz;} /* Function to print linked list */static void printList(Node node){    while (node.next != null)    {        System.out.print(        node.data + " " + "<=>" + " ");        node = node.next;    }    System.out.print(node.data);} // Function to insert a node at the// beginning of the Doubly Linked Liststatic Node push(Node head_ref,                 char new_data){    Node new_node = new Node();    new_node.data = new_data;    new_node.prev = null;    new_node.next = head_ref;    if (head_ref != null)        head_ref.prev = new_node;    head_ref = new_node;    return head_ref;} // Function to rotate a doubly linked// list clockwise and update the headstatic Node rotate(Node head_ref,                   int N, int sz){     /* If N is greater than the size of    Doubly Linked List, we have to deduce it    in the range of Doubly linked list size    by taking modulo with the length of the list.*/    N = N % sz;     /* We will update N by subtracting    it's value length of the list.    After this the question will    reduce to counter clockwise rotation    of linked list to N places*/    N = sz - N;     if (N == 0)        return null;     Node current = head_ref;     // current will either point to Nth    // or null after this loop. Current    // will point to node 'b' in the    // above example    int count = 1;    while (count < N && current != null)    {        current = current.next;        count++;    }     // If current is null, N is greater    // than or equal to count of nodes    // in linked list    // Don't change the list in this case    if (current == null)        return null;     // current points to Nth node. Store    // it in a variable. NthNode points to    // node 'b' in the above example    Node NthNode = current;     // current will point to last node    // after this loop current will point    // to node 'e' in the above example    while (current.next != null)        current = current.next;     // Change next of last node to previous    // head. Next of 'e' is now changed to    // node 'a'    current.next = head_ref;     // Change prev of Head node to current    // Prev of 'a' is now changed to node 'e'    head_ref.prev = current;     // Change head to (N+1)th node    // head is now changed to node 'c'    head_ref = NthNode.next;     // Change prev of New Head node to null    // Because Prev of Head Node in Doubly    // linked list is null    head_ref.prev = null;     // Change next of Nth node to null    // next of 'b' is now null    NthNode.next = null;    return head_ref;} // Driver codepublic static void main(String []args){    /* Start with the empty list */    Node head = null;     /* Create the doubly linked    list a<->b<->c<->d<->e */    head = push(head, 'e');    head = push(head, 'd');    head = push(head, 'c');    head = push(head, 'b');    head = push(head, 'a');     int N = 2;     // Length of the list    int sz = size(head);     System.out.println("Given Doubly linked list ");    printList(head);    head = rotate(head, N, sz);     System.out.println("\nRotated Linked list clockwise ");    printList(head);}} // This code is contributed by 29AjayKumar
# Node of a doubly linked listclass Node:    def __init__(self, next = None,                    prev = None, data = None):        self.next = next # reference to next node in DLL        self.prev = prev # reference to previous node in DLL        self.data = data # Function to insert a node at the# beginning of the Doubly Linked Listdef push(head, new_data):     new_node = Node(data = new_data)     new_node.next = head    new_node.prev = None     if head is not None:        head.prev = new_node     head = new_node    return head # Utility function to find the size of# Doubly Linked Listdef size(head):    node = head    sz = 0    while(node is not None):        sz+= 1        node = node.next    return sz # Function to print linked listdef printList(head):     node = head     print("Given linked list")    while(node is not None):        print(node.data, end = " "),        last = node        node = node.next # Function to rotate a doubly linked# list clockwise and update the headdef rotate(start, N):    if N == 0 :        return     # Let us understand the below code    # for example N = 2 and    # list = a <-> b <-> c <-> d <-> e.    current = start     # current will either point to Nth    # or None after this loop. Current    # will point to node 'b' in the    # above example    count = 1    while count < N and current != None :        current = current.next        count += 1     # If current is None, N is greater    # than or equal to count of nodes    # in linked list. Don't change the    # list in this case    if current == None :        return     # current points to Nth node. Store    # it in a variable. NthNode points to    # node 'b' in the above example    NthNode = current     # current will point to last node    # after this loop current will point    # to node 'e' in the above example    while current.next != None :        current = current.next     # Change next of last node to previous    # head. Next of 'e' is now changed to    # node 'a'    current.next = start     # Change prev of Head node to current    # Prev of 'a' is now changed to node 'e'    start.prev = current     # Change head to (N + 1)th node    # head is now changed to node 'c'    start = NthNode.next     # Change prev of New Head node to None    # Because Prev of Head Node in Doubly    # linked list is None    start.prev = None     # change next of Nth node to None    # next of 'b' is now None    NthNode.next = None     return start # Driver Codeif __name__ == "__main__":    head = None     head = push(head, 'e')    head = push(head, 'd')    head = push(head, 'c')    head = push(head, 'b')    head = push(head, 'a')     printList(head)    print("\n")         N = 2     # Length of the list    sz = size(head)     # If N is greater than the size of Doubly    # Linked List, we have to deduce it in the range    # of Doubly linked list size by taking modulo with the    # length of the list.    N = N % sz;         # We will update N by subtracting it's value length of    # the list. After this the question will reduce to    # counter-clockwise rotation of linked list to N places    N = sz-N;         head = rotate(head, N)     printList(head)
// C# program to rotate a Doubly linked// list clock wise by N timesusing System;     class GFG{ /* Link list node */public class Node{    public char data;    public Node prev;    public Node next;}; // Utility function to find the size of// Doubly Linked Liststatic int size(Node head_ref){    Node curr = head_ref;    int sz = 0;    while (curr != null)    {        curr = curr.next;        sz++;    }    return sz;} /* Function to print linked list */static void printList(Node node){    while (node.next != null)    {        Console.Write(        node.data + " " + "<=>" + " ");        node = node.next;    }    Console.Write(node.data);} // Function to insert a node at the// beginning of the Doubly Linked Liststatic Node push(Node head_ref,                 char new_data){    Node new_node = new Node();    new_node.data = new_data;    new_node.prev = null;    new_node.next = head_ref;    if (head_ref != null)        head_ref.prev = new_node;    head_ref = new_node;    return head_ref;} // Function to rotate a doubly linked// list clockwise and update the headstatic Node rotate(Node head_ref,                   int N, int sz){     /* If N is greater than the size of    Doubly Linked List, we have to deduce it    in the range of Doubly linked list size    by taking modulo with the length of the list.*/    N = N % sz;     /* We will update N by subtracting    it's value length of the list.    After this the question will    reduce to counter clockwise rotation    of linked list to N places*/    N = sz - N;     if (N == 0)        return null;     Node current = head_ref;     // current will either point to Nth    // or null after this loop. Current    // will point to node 'b' in the    // above example    int count = 1;    while (count < N && current != null)    {        current = current.next;        count++;    }     // If current is null, N is greater    // than or equal to count of nodes    // in linked list    // Don't change the list in this case    if (current == null)        return null;     // current points to Nth node. Store    // it in a variable. NthNode points to    // node 'b' in the above example    Node NthNode = current;     // current will point to last node    // after this loop current will point    // to node 'e' in the above example    while (current.next != null)        current = current.next;     // Change next of last node to previous    // head. Next of 'e' is now changed to    // node 'a'    current.next = head_ref;     // Change prev of Head node to current    // Prev of 'a' is now changed to node 'e'    head_ref.prev = current;     // Change head to (N+1)th node    // head is now changed to node 'c'    head_ref = NthNode.next;     // Change prev of New Head node to null    // Because Prev of Head Node in Doubly    // linked list is null    head_ref.prev = null;     // Change next of Nth node to null    // next of 'b' is now null    NthNode.next = null;    return head_ref;} // Driver codepublic static void Main(String []args){    /* Start with the empty list */    Node head = null;     /* Create the doubly linked    list a<->b<->c<->d<->e */    head = push(head, 'e');    head = push(head, 'd');    head = push(head, 'c');    head = push(head, 'b');    head = push(head, 'a');     int N = 2;     // Length of the list    int sz = size(head);     Console.WriteLine("Given Doubly linked list ");    printList(head);    head = rotate(head, N, sz);     Console.WriteLine("\nRotated Linked list clockwise ");    printList(head);}} // This code is contributed by Rajput-Ji
<script> // Javascript program to rotate a Doubly linked// list clock wise by N times /* Link list node */class Node {        constructor() {                this.data = null;                this.prev = null;                this.next = null;             }        }         // Utility function to find the size of// Doubly Linked Listfunction size( head_ref){    var curr = head_ref;    let sz = 0;    while (curr != null)    {        curr = curr.next;        sz++;    }    return sz;} /* Function to print linked list */function printList( node){    while (node.next != null)    {        document.write(        node.data + " " + "<=>" + " ");        node = node.next;    }    document.write(node.data);} // Function to insert a node at the// beginning of the Doubly Linked Listfunction push( head_ref, new_data){    var new_node = new Node();    new_node.data = new_data;    new_node.prev = null;    new_node.next = head_ref;    if (head_ref != null)        head_ref.prev = new_node;    head_ref = new_node;    return head_ref;} // Function to rotate a doubly linked// list clockwise and update the headfunction rotate( head_ref, N, sz){     /* If N is greater than the size of    Doubly Linked List, we have to deduce it    in the range of Doubly linked list size    by taking modulo with the length of the list.*/    N = N % sz;     /* We will update N by subtracting    it's value length of the list.    After this the question will    reduce to counter clockwise rotation    of linked list to N places*/    N = sz - N;     if (N == 0)        return null;     var current = head_ref;     // current will either point to Nth    // or null after this loop. Current    // will point to node 'b' in the    // above example    let count = 1;    while (count < N && current != null)    {        current = current.next;        count++;    }     // If current is null, N is greater    // than or equal to count of nodes    // in linked list    // Don't change the list in this case    if (current == null)        return null;     // current points to Nth node. Store    // it in a variable. NthNode points to    // node 'b' in the above example    var NthNode = current;     // current will point to last node    // after this loop current will point    // to node 'e' in the above example    while (current.next != null)        current = current.next;     // Change next of last node to previous    // head. Next of 'e' is now changed to    // node 'a'    current.next = head_ref;     // Change prev of Head node to current    // Prev of 'a' is now changed to node 'e'    head_ref.prev = current;     // Change head to (N+1)th node    // head is now changed to node 'c'    head_ref = NthNode.next;     // Change prev of New Head node to null    // Because Prev of Head Node in Doubly    // linked list is null    head_ref.prev = null;     // Change next of Nth node to null    // next of 'b' is now null    NthNode.next = null;    return head_ref;}  // Driver Code /* Start with the empty list */var head = null; /* Create the doubly linkedlist a<->b<->c<->d<->e */head = push(head, 'e');head = push(head, 'd');head = push(head, 'c');head = push(head, 'b');head = push(head, 'a'); let N = 2; // Length of the listlet sz = size(head); document.write("Given Doubly linked list ");document.write("<br>");printList(head);head = rotate(head, N, sz); document.write("</br>"+"Rotated Linked list clockwise ");document.write("<br>");printList(head);     </script>
Given Doubly linked list 
a <=> b <=> c <=> d <=> e
Rotated Linked list clockwise 
d <=> e <=> a <=> b <=> c
 
Time Complexity: O(n) where n is the number of nodes in Linked List. 
29AjayKumar
Rajput-Ji
jana_sayantan
doubly linked list
Linked List
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Circular Linked List | Set 2 (Traversal)
Swap nodes in a linked list without swapping data
Circular Singly Linked List | Insertion
Given a linked list which is sorted, how will you insert in sorted way
Program to implement Singly Linked List in C++ using class
Delete a node in a Doubly Linked List
Real-time application of Data Structures
Insert a node at a specific position in a linked list
Linked List Implementation in C#
Priority Queue using Linked List