Open In App

Python3 Program to Rotate the sub-list of a linked list from position M to N to the right by K places

Last Updated : 31 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a linked list and two positions ‘m’ and ‘n’. The task is to rotate the sublist from position m to n, to the right by k places. Examples:

Input: list = 1->2->3->4->5->6, m = 2, n = 5, k = 2 Output: 1->4->5->2->3->6 Rotate the sublist 2 3 4 5 towards right 2 times then the modified list are: 1 4 5 2 3 6 Input: list = 20->45->32->34->22->28, m = 3, n = 6, k = 3 Output: 20->45->34->22->28->32 Rotate the sublist 32 34 22 28 towards right 3 times then the modified list are: 20 45 34 22 28 32

Approach: For rotating the given sublist that extends from m to n element, move the list from (n-k+1)th to nth node to starting of sub-list to finish the rotation. If k is greater than size of sublist then we will take its modulo with size of sublist. So traverse through list using a pointer and a counter and we will save (m-1)th node and later make it point to (n-k+1)th node and hence bring (n-k+1)th node to the start(front) of sublist. Similarly we will save mth node and later make nth node point to it. And for keeping rest of list intact we will make (n-k)th node point to next node of n (maybe NULL). And finally we will get the k times right rotated sublist. Below is the implementation of the above approach: 

Python3




# Python3 implementation of the above approach
import math
 
# Definition of node of linkedlist
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None
 
# This function take head pointer of list,
# start and end points of sublist that is
# to be rotated and the number k and
# rotate the sublist to right by k places.
def rotateSubList(A, m, n, k):
    size = n - m + 1
 
    # If k is greater than size of sublist then
    # we will take its modulo with size of sublist
    if (k > size):
        k = k % size
     
    # If k is zero or k is equal to size or k is
    # a multiple of size of sublist then list
    # remains intact
    if (k == 0 or k == size):
        head = A
        while (head != None):
            print(head.data)
            head = head.next
         
        return
     
    link = None # m-th node
    if (m == 1) :
        link = A
     
    # This loop will traverse all node till
    # end node of sublist.
    c = A # Current traversed node
    count = 0 # Count of traversed nodes
    end = None
    pre = None # Previous of m-th node
    while (c != None) :
        count = count + 1
 
        # We will save (m-1)th node and later
        # make it point to (n-k+1)th node
        if (count == m - 1) :
            pre = c
            link = c.next
         
        if (count == n - k) :
            if (m == 1) :
                end = c
                A = c.next
             
            else :
                end = c
 
                # That is how we bring (n-k+1)th
                # node to front of sublist.
                pre.next = c.next
             
        # This keeps rest part of list intact.
        if (count == n) :
            d = c.next
            c.next = link
            end.next = d
            head = A
            while (head != None) :
                print(head.data, end = " ")
                head = head.next
             
            return
         
        c = c.next
     
# Function for creating and linking new nodes
def push(head, val):
    new_node = Node(val)
    new_node.data = val
    new_node.next = head
    head = new_node
    return head
 
# Driver code
if __name__=='__main__':
    head = None
    head = push(head, 70)
    head = push(head, 60)
    head = push(head, 50)
    head = push(head, 40)
    head = push(head, 30)
    head = push(head, 20)
    head = push(head, 10)
    tmp = head
    print("Given List: ", end = "")
    while (tmp != None) :
        print(tmp.data, end = " ")
        tmp = tmp.next
     
    print()
 
    m = 3
    n = 6
    k = 2
    print("After rotation of sublist: ", end = "")
    rotateSubList(head, m, n, k)
 
# This code is contributed by Srathore


Output:

Given List: 10 20 30 40 50 60 70 
After rotation of sublist: 10 20 50 60 30 40 70

Time complexity: O(N) where N is the size of the given linked list

Auxiliary space: O(1) because it is using constant space

Please refer complete article on Rotate the sub-list of a linked list from position M to N to the right by K places for more details!



Similar Reads

C++ Program to Rotate the sub-list of a linked list from position M to N to the right by K places
Given a linked list and two positions 'm' and 'n'. The task is to rotate the sublist from position m to n, to the right by k places. Examples: Input: list = 1->2->3->4->5->6, m = 2, n = 5, k = 2 Output: 1->4->5->2->3->6 Rotate the sublist 2 3 4 5 towards right 2 times then the modified list are: 1 4 5 2 3 6 Input: list
4 min read
Java Program to Rotate the sub-list of a linked list from position M to N to the right by K places
Given a linked list and two positions 'm' and 'n'. The task is to rotate the sublist from position m to n, to the right by k places. Examples: Input: list = 1->2->3->4->5->6, m = 2, n = 5, k = 2 Output: 1->4->5->2->3->6 Rotate the sublist 2 3 4 5 towards right 2 times then the modified list are: 1 4 5 2 3 6 Input: list
4 min read
Rotate the sub-list of a linked list from position M to N to the right by K places
Given a linked list and two positions 'm' and 'n'. The task is to rotate the sublist from position m to n, to the right by k places.Examples: Input: list = 1->2->3->4->5->6, m = 2, n = 5, k = 2 Output: 1->4->5->2->3->6 Rotate the sublist 2 3 4 5 towards right 2 times then the modified list are: 1 4 5 2 3 6 Input: list
13 min read
Python3 Program to Rotate the matrix right by K times
Given a matrix of size N*M, and a number K. We have to rotate the matrix K times to the right side. Examples: Input : N = 3, M = 3, K = 2 12 23 34 45 56 67 78 89 91 Output : 23 34 12 56 67 45 89 91 78 Input : N = 2, M = 2, K = 2 1 2 3 4 Output : 1 2 3 4 A simple yet effective approach is to consider each row of the matrix as an array and perform an
2 min read
Python3 Program to Rotate all odd numbers right and all even numbers left in an Array of 1 to N
Given a permutation arrays A[] consisting of N numbers in range [1, N], the task is to left rotate all the even numbers and right rotate all the odd numbers of the permutation and print the updated permutation. Note: N is always even.Examples:  Input: A = {1, 2, 3, 4, 5, 6, 7, 8} Output: {7, 4, 1, 6, 3, 8, 5, 2} Explanation: Even element = {2, 4, 6
2 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 = 2 Output : c d e a b Input : a b c d e f g h N = 4 Output : e f g h a b c d Asked in Amazon To rotate the Doubly linked list, we
4 min read
Python3 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 = 1 Output: 3->1->2->6->4->5->9->7->8->NULL Explan
3 min read
Python3 Program for Check if a string can be obtained by rotating another string d places
Given two strings str1 and str2 and an integer d, the task is to check whether str2 can be obtained by rotating str1 by d places (either to the left or to the right). Examples: Input: str1 = "abcdefg", str2 = "cdefgab", d = 2 Output: Yes Rotate str1 2 places to the left. Input: str1 = "abcdefg", str2 = "cdfdawb", d = 6 Output: No Approach: An appro
3 min read
Python3 Program to Check if a string can be obtained by rotating another string 2 places
Given two strings, the task is to find if a string can be obtained by rotating another string two places. Examples: Input: string1 = "amazon", string2 = "azonam" Output: Yes // rotated anti-clockwiseInput: string1 = "amazon", string2 = "onamaz" Output: Yes // rotated clockwise Asked in: Amazon Interview Recommended: Please solve it on “PRACTICE ” f
2 min read
Python | Get a set of places according to search query using Google Places API
Google Places API Web Service allow the user to query for place information on a variety of categories, such as establishments, prominent points of interest, geographic locations, and more. One can search for places either by proximity or a text string. A Place Search returns a list of places along with summary information about each place; additio
3 min read
Article Tags :
Practice Tags :