Rotate a Linked List | C ++ program to rotate a linked list counter clock wise ; Link list node ; This function rotates a linked list counter - clockwise and updates the head . The function assumes that k is smaller than size of linked list . ; Let us understand the below code for example k = 4 and list = 10 -> 20 -> 30 -> 40 -> 50 -> 60. ; Traverse till the end . ; traverse the linked list to k - 1 position which will be last element for rotated array . ; update the head_ref and last element pointer to NULL ; Function to push a node ; allocate node ; put in the data ; link the old list off the new node ; move the head to point to the new node ; Function to print linked list ; Driver code ; Start with the empty list ; create a list 10 -> 20 -> 30 -> 40 -> 50 -> 60
#include <bits/stdc++.h> NEW_LINE using namespace std ; class Node { public : int data ; Node * next ; } ; void rotate ( Node * * head_ref , int k ) { if ( k == 0 ) return ; Node * current = * head_ref ; while ( current -> next != NULL ) current = current -> next ; current -> next = * head_ref ; current = * head_ref ; for ( int i = 0 ; i < k - 1 ; i ++ ) current = current -> next ; * head_ref = current -> next ; current -> next = NULL ; } void push ( Node * * head_ref , int new_data ) { Node * new_node = new Node ( ) ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } void printList ( Node * node ) { while ( node != NULL ) { cout << node -> data << " ▁ " ; node = node -> next ; } } int main ( void ) { Node * head = NULL ; for ( int i = 60 ; i > 0 ; i -= 10 ) push ( & head , i ) ; cout << " Given ▁ linked ▁ list ▁ STRNEWLINE " ; printList ( head ) ; rotate ( & head , 4 ) ; cout << " Rotated Linked list " ; printList ( head ) ; return ( 0 ) ; }