Rotate the sub | C ++ implementation of the above approach ; Definition of node of linkedlist ; 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 . ; If k is greater than size of sublist then we will take its modulo with size of sublist ; If k is zero or k is equal to size or k is a multiple of size of sublist then list remains intact ; m - th node ; This loop will traverse all node till end node of sublist . Current traversed node ; Count of traversed nodes ; Previous of m - th node ; We will save ( m - 1 ) th node and later make it point to ( n - k + 1 ) th node ; That is how we bring ( n - k + 1 ) th node to front of sublist . ; This keeps rest part of list intact . ; Function for creating and linking new nodes ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct ListNode { int data ; struct ListNode * next ; } ; void rotateSubList ( ListNode * A , int m , int n , int k ) { int size = n - m + 1 ; if ( k > size ) { k = k % size ; } if ( k == 0 k == size ) { ListNode * head = A ; while ( head != NULL ) { cout << head -> data ; head = head -> next ; } return ; } ListNode * link = NULL ; if ( m == 1 ) { link = A ; } ListNode * c = A ; int count = 0 ; ListNode * end = NULL ; ListNode * pre = NULL ; while ( c != NULL ) { count ++ ; if ( count == m - 1 ) { pre = c ; link = c -> next ; } if ( count == n - k ) { if ( m == 1 ) { end = c ; A = c -> next ; } else { end = c ; pre -> next = c -> next ; } } if ( count == n ) { ListNode * d = c -> next ; c -> next = link ; end -> next = d ; ListNode * head = A ; while ( head != NULL ) { cout << head -> data << " ▁ " ; head = head -> next ; } return ; } c = c -> next ; } } void push ( struct ListNode * * head , int val ) { struct ListNode * new_node = new ListNode ; new_node -> data = val ; new_node -> next = ( * head ) ; ( * head ) = new_node ; } int main ( ) { struct ListNode * head = NULL ; push ( & head , 70 ) ; push ( & head , 60 ) ; push ( & head , 50 ) ; push ( & head , 40 ) ; push ( & head , 30 ) ; push ( & head , 20 ) ; push ( & head , 10 ) ; ListNode * tmp = head ; cout << " Given ▁ List : ▁ " ; while ( tmp != NULL ) { cout << tmp -> data << " ▁ " ; tmp = tmp -> next ; } cout << endl ; int m = 3 , n = 6 , k = 2 ; cout << " After ▁ rotation ▁ of ▁ sublist : ▁ " ; rotateSubList ( head , m , n , k ) ; return 0 ; }