Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Linked List
  • Practice Linked List
  • MCQs on Linked List
  • Linked List Tutorial
  • Types of Linked List
  • Singly Linked List
  • Doubly Linked List
  • Circular Linked List
  • Circular Doubly Linked List
  • Linked List vs Array
  • Time & Space Complexity
  • Advantages & Disadvantages
Open In App
Next Article:
Count rotations in sorted and rotated linked list
Next article icon

Rotate Linked List block wise

Last Updated : 15 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a Linked List of length n and block length k rotate in a circular manner towards right/left each block by a number d. If d is positive rotate towards right else rotate towards left.

Examples: 

Input: 1->2->3->4->5->6->7->8->9->NULL,          k = 3          d = 1 Output: 3->1->2->6->4->5->9->7->8->NULL Explanation: Here blocks of size 3 are rotated towards right(as d is positive)  by 1.   Input: 1->2->3->4->5->6->7->8->9->10->                11->12->13->14->15->NULL,          k = 4          d = -1 Output: 2->3->4->1->6->7->8->5->10->11              ->12->9->14->15->13->NULL Explanation: Here, at the end of linked  list, remaining nodes are less than k, i.e. only three nodes are left while k is 4.  Rotate those 3 nodes also by d.

Prerequisite: Rotate a linked list
The idea is if the absolute value of d is greater than the value of k, then rotate the link list by d % k times. If d is 0, no need to rotate the linked list at all. 

C++




 
 

C




// C program to rotate a linked list block wise
#include <stdio.h>
#include <stdlib.h>
 
/* Link list node */
struct Node {
    int data;
    struct Node* next;
};
 
// Recursive function to rotate one block
struct Node* rotateHelper(struct Node* blockHead,
                          struct Node* blockTail,
                          int d, struct Node** tail,
                          int k)
{
    if (d == 0)
        return blockHead;
 
    // Rotate Clockwise
    if (d > 0) {
        struct Node* temp = blockHead;
        for (int i = 1; temp->next->next &&
                        i < k - 1; i++)
            temp = temp->next;
        blockTail->next = blockHead;
        *tail = temp;
        return rotateHelper(blockTail, temp,
                            d - 1, tail, k);
    }
 
    // Rotate anti-Clockwise
    if (d < 0) {
        blockTail->next = blockHead;
        *tail = blockHead;
        return rotateHelper(blockHead->next,
                blockHead, d + 1, tail, k);
    }
}
 
// Function to rotate the linked list block wise
struct Node* rotateByBlocks(struct Node* head,
                                 int k, int d)
{
    // If length is 0 or 1 return head
    if (!head || !head->next)
        return head;
 
    // if degree of rotation is 0, return head
    if (d == 0)
        return head;
 
    struct Node* temp = head, *tail = NULL;
 
    // Traverse upto last element of this block
    int i;
    for (i = 1; temp->next && i < k; i++)
        temp = temp->next;
 
    // storing the first node of next block
    struct Node* nextBlock = temp->next;
 
    // If nodes of this block are less than k.
    // Rotate this block also
    if (i < k)
        head = rotateHelper(head, temp, d % k,
                                    &tail, i);
    else
        head = rotateHelper(head, temp, d % k,
                                    &tail, k);
 
    // Append the new head of next block to
    // the tail of this block
    tail->next = rotateByBlocks(nextBlock, k,
                                      d % k);
 
    // return head of updated Linked List
    return head;
}
 
/* UTILITY FUNCTIONS */
/* Function to push a node */
void push(struct Node** head_ref, int new_data)
{
    struct Node* new_node = new Node;
    new_node->data = new_data;
    new_node->next = (*head_ref);
    (*head_ref) = new_node;
}
 
/* Function to print linked list */
void printList(struct Node* node)
{
    while (node != NULL) {
        printf("%d ", node->data);
        node = node->next;
    }
}
 
/* Driver program to test above function*/
int main()
{
    /* Start with the empty list */
    struct Node* head = NULL;
 
    // create a list 1->2->3->4->5->
    // 6->7->8->9->NULL
    for (int i = 9; i > 0; i -= 1)
        push(&head, i);
 
    printf("Given linked list \n");
    printList(head);
 
    // k is block size and d is number of
    // rotations in every block.
    int k = 3, d = 2;
    head = rotateByBlocks(head, k, d);
 
    printf("\nRotated by blocks Linked list \n");
    printList(head);
 
    return (0);
}
 
 

Java




 
 

Python3




 
 

C#




 
 

Javascript




 
 

Output:

Given linked list  1 2 3 4 5 6 7 8 9  Rotated by blocks Linked list  2 3 1 5 6 4 8 9 7

Time complexity: O(n) since using a single loop to traverse a linked list to rotate

Auxiliary Space: O(n) for call stack

 



Next Article
Count rotations in sorted and rotated linked list
https://media.geeksforgeeks.org/auth/avatar.png
GeeksforGeeks
Improve
Article Tags :
  • DSA
  • Linked List
  • rotation
Practice Tags :
  • Linked List

Similar Reads

  • Rotate a Linked List
    Given a singly linked list and an integer k, the task is to rotate the linked list to the left by k places. Examples: Input: linked list = 10 -> 20 -> 30 -> 40 -> 50, k = 4Output: 50 -> 10 -> 20 -> 30 -> 40 Explanation: After rotating the linked list to the left by 4 places,
    15+ min read
  • Clockwise rotation of Linked List
    Given a singly linked list and an integer K, the task is to rotate the linked list clockwise to the right by K places.Examples: Input: 1 -> 2 -> 3 -> 4 -> 5 -> NULL, K = 2 Output: 4 -> 5 -> 1 -> 2 -> 3 -> NULLInput: 7 -> 9 -> 11 -> 13 -> 3 -> 5 -> NULL
    15+ min read
  • Javascript Program to Rotate Linked List block wise
    Given a Linked List of length n and block length k rotate in a circular manner towards right/left each block by a number d. If d is positive rotate towards right else rotate towards left. Examples: Input: 1->2->3->4->5->6->7->8->9->NULL, k = 3 d = 1Output: 3->1->2-
    3 min read
  • Rotate Doubly linked list by N nodes
    Given a doubly-linked list, the task is to rotate the linked list counter-clockwise by p nodes. Here p is a given positive integer and is smaller than the count of nodes in the linked list. Examples: Input: Output: Explanation: After rotating the list by p = 2, the new head will be the node with val
    12 min read
  • Count rotations in sorted and rotated linked list
    Given a linked list of n nodes which is first sorted, then rotated by k elements. Find the value of k. The idea is to traverse singly linked list to check condition whether current node value is greater than value of next node. If the given condition is true, then break the loop. Otherwise increase
    8 min read
  • Clockwise rotation of Doubly Linked List by N places
    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 t
    15+ min read
  • Rotate a Matrix k Times Clockwise
    Given a matrix of order m*n and a value k, the task is to rotate each ring of the matrix clockwise by k. Examples: Input :k = 3 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16Output: 13 9 5 114 10 6 215 11 7 316 12 8 4 Input : k = 2 1 2 3 410 11 12 5 9 8 7 6Output: 9 10 1 2 8 11 12 3 7 6 5 4 Naive Solution -
    15+ min read
  • Javascript Program For Rotating A Linked List
    Given a singly linked list, rotate the linked list counter-clockwise by k nodes. Where k is a given positive integer. For example, if the given linked list is 10->20->30->40->50->60 and k is 4, the list should be modified to 50->60->10->20->30->40. Assume that k is smal
    5 min read
  • Left rotate Linked List by X in groups of Y nodes
    Given a singly linked list and two integers X and Y, the task is to left rotate the linked list by X in groups of Y nodes. Examples: Input: 10 -> 20 -> 30 -> 40 -> 50 -> 60 -> 70 -> 80 -> 90 -> 100, X = 2, Y = 4Output: 30 -> 40 -> 10 -> 20 -> 70 -> 80 ->
    10 min read
  • Rotate Matrix Clockwise by 1
    Given a square matrix, the task is to rotate its elements clockwise by one step. Examples: Input 1 2 34 5 6 7 8 9Output: 4 1 27 5 3 8 9 6 Input: 1 2 3 4 5 6 7 8 9 10 11 1213 14 15 16 Output: 5 1 2 3 9 10 6 4 13 11 7 8 14 15 16 12 The idea is to use nested loops to move elements in four directions (r
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
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
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences