Java Program For Rotating A Linked List
Given a singly linked list, rotate the linked list counter-clockwise by k nodes. Where k is a given positive integer. For example, if the given linked list is 10->20->30->40->50->60 and k is 4, the list should be modified to 50->60->10->20->30->40. Assume that k is smaller than the count of nodes in a linked list.
Method 1:
To rotate the linked list, we need to change the next of kth node to NULL, the next of the last node to the previous head node, and finally, change the head to (k+1)th node. So we need to get hold of three nodes: kth node, (k+1)th node, and last node.
Traverse the list from the beginning and stop at kth node. Store pointer to kth node. We can get (k+1)th node using kthNode->next. Keep traversing till the end and store a pointer to the last node also. Finally, change pointers as stated above.
Below image shows how to rotate function works in the code :
Output:
Given linked list
10 20 30 40 50 60
Rotated Linked list
50 60 10 20 30 40
Time Complexity: O(n) where n is the number of nodes in Linked List. The code traverses the linked list only once.
Auxiliary Space: O(1) as it is using constant space
Method 2:
To rotate a linked list by k, we can first make the linked list circular and then moving k-1 steps forward from head node, making (k-1)th node’s next to null and make kth node as head.
Java
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 " );
printList(head);
rotate( 4 );
System.out.print(
"Rotated Linked list " );
printList(head);
}
}
|
Output:
Given linked list
10 20 30 40 50 60
Rotated Linked list
50 60 10 20 30 40
Please refer complete article on Rotate a Linked List for more details!
Last Updated :
01 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...