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
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Program For Rotating A Linked List
Next article icon

Python3 Program To Rotate Linked List Block Wise

Last Updated : 05 Sep, 2024
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. 

Python
# Python3 program to rotate a linked # list block wise   # Link list node  class Node:         def __init__(self, data):               self.data = data         self.next = None  # Recursive function to rotate one block  def rotateHelper(blockHead, blockTail,                  d, tail, k):         if (d == 0):         return blockHead, tail        # Rotate Clockwise      if (d > 0):         temp = blockHead          i = 1                 while (temp.next.next != None and                 i < k - 1):             temp = temp.next             i += 1                     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  def rotateByBlocks(head, k, d):      # If length is 0 or 1 return head      if (head == None or head.next == None):         return head       # If degree of rotation is 0, return head      if (d == 0):         return head      temp = head     tail = None       # Traverse upto last element of this block      i = 1         while temp.next != None and i < k:         temp = temp.next          i += 1       # Storing the first node of next block      nextBlock = temp.next       # If nodes of this block are less than k.      # Rotate this block also      if (i < k):         head, tail = rotateHelper(head, temp,                                    d % k, tail, i)      else:         head, tail = 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  def push(head_ref, new_data):      new_node = Node(new_data)     new_node.data = new_data      new_node.next = (head_ref)      (head_ref) = new_node     return head_ref  # Function to print linked list  def printList(node):     while (node != None):         print(node.data, end = ' ')         node = node.next       # Driver code if __name__=='__main__':          # Start with the empty list     head = None       # Create a list 1.2.3.4.5.      # 6.7.8.9.None      for  i in range(9, 0, -1):         head = push(head, i)      print("Given linked list ")     printList(head)       # k is block size and d is number      # of rotations in every block.      k = 3     d = 2     head = rotateByBlocks(head, k, d)       print(     "Rotated by blocks Linked list ")     printList(head)  # This code is contributed by rutvik_56 

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) where n is no of node in given linked list

Please refer complete article on Rotate Linked List block wise for more details!



Next Article
Python Program For Rotating A Linked List
author
kartik
Improve
Article Tags :
  • DSA
  • Linked List
  • Python
  • Python Programs
  • rotation
Practice Tags :
  • Linked List
  • python

Similar Reads

  • Python 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 smaller than the count of nodes in
    5 min read
  • Python3 Program to Rotate Doubly linked list by N nodes
    Given a doubly linked list, rotate the linked list counter-clockwise by N nodes. Here N is a given positive integer and is smaller than the count of nodes in linked list.   N = 2Rotated List:   Examples:   Input : a b c d e N = 2Output : c d e a b Input : a b c d e f g h N = 4Output : e f g h a b c
    4 min read
  • Python3 Program for Clockwise rotation of Linked List
    Write a Python3 program for a given 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 -> 1
    5 min read
  • Python Program to Implement Stack Using Linked List
    In Python, creating a stack using a linked list involves implementing a data structure where elements are added and removed in a last-in-first-out (LIFO) manner. This approach uses the concept of nodes interconnected by pointers, allowing efficient insertion and deletion operations. We are given a L
    4 min read
  • Python3 Program to 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
    3 min read
  • Python Program For Reversing A Doubly Linked List
    Given a Doubly Linked List, the task is to reverse the given Doubly Linked List. See below diagrams for example.  (a) Original Doubly Linked List (b) Reversed Doubly Linked List Here is a simple method for reversing a Doubly Linked List. All we need to do is swap prev and next pointers for all nodes
    4 min read
  • Python3 Program to Rotate bits of a number
    Bit Rotation: A rotation (or circular shift) is an operation similar to a shift except that the bits that fall off at one end are put back to the other end. In the left rotation, the bits that fall off at the left end are put back at the right end. In the right rotation, the bits that fall off at th
    3 min read
  • Python Program For QuickSort On Doubly Linked List
    Following is a typical recursive implementation of QuickSort for arrays. The implementation uses last element as pivot. C/C++ Code """A typical recursive implementation of Quicksort for array """ """ This function takes last element as pivot, places the p
    5 min read
  • Python - Ways to rotate a list
    Rotating a list means shifting its elements to the left or right by a certain number of positions. In this article, we will explore Various ways to rotate a list The simplest way to rotate a list is by using slicing. Slicing allows us to break the list into two parts and rearrange them. [GFGTABS] Py
    2 min read
  • Python Program to Rotate Matrix Elements
    Given a matrix, clockwise rotate elements in it. Examples: Input 1 2 3 4 5 6 7 8 9 Output: 4 1 2 7 5 3 8 9 6 For 4*4 matrix Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output: 5 1 2 3 9 10 6 4 13 11 7 8 14 15 16 12Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.
    3 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