Rotate a Linked List | Java 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 ; create a list 10.20 . 30.40 .50 . 60
import java . util . * ; class GFG { static class Node { int data ; Node next ; } ; static Node head = null ; static void rotate ( int k ) { if ( k == 0 ) return ; Node current = head ; while ( current . next != null ) current = current . next ; current . next = head ; current = head ; for ( int i = 0 ; i < k - 1 ; i ++ ) current = current . next ; head = current . next ; current . next = null ; } static void push ( int new_data ) { Node new_node = new Node ( ) ; new_node . data = new_data ; new_node . next = head ; head = new_node ; } static void printList ( Node node ) { while ( node != null ) { System . out . print ( node . data + " ▁ " ) ; node = node . next ; } } public static void main ( String [ ] args ) { for ( int i = 60 ; i > 0 ; i -= 10 ) push ( i ) ; System . out . print ( "Given linked list NEW_LINE"); printList ( head ) ; rotate ( 4 ) ; System . out . print ( " Rotated Linked list "); printList ( head ) ; } }