Given a Linked List of length n and block length k rotate in circular manner towards right/left each block by a number d. If d is positive rotate towards right else rotate towards left.
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.
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
This article is contributed by Chhavi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Rotate the sub-list of a linked list from position M to N to the right by K places
- Rotate a Linked List
- Rotate Doubly linked list by N nodes
- Flatten a multi-level linked list | Set 2 (Depth wise)
- Create new linked list from two given linked list with greater element at each node
- Python | Ways to rotate a list
- Merge a linked list into another linked list at alternate positions
- Convert singly linked list into circular linked list
- Difference between Singly linked list and Doubly linked list
- XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
- XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
- Check if a linked list is Circular Linked List
- Convert Singly Linked List to XOR Linked List
- Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes
- Create a linked list from two linked lists by choosing max element at each position
- Construct a Doubly linked linked list from 2D Matrix
- Length of longest palindrome list in a linked list using O(1) extra space
- Partitioning a linked list around a given value and If we don't care about making the elements of the list "stable"
- Linked List | Set 1 (Introduction)
- Linked List Sum of Nodes Between 0s