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 firstname.lastname@example.org. 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.
- 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)
- Python | Ways to rotate a list
- Create new linked list from two given linked list with greater element at each node
- XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
- XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
- Convert singly linked list into circular linked list
- Merge a linked list into another linked list at alternate positions
- Difference between Singly linked list and Doubly linked list
- Convert Singly Linked List to XOR Linked List
- Check if a linked list is Circular 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