Clockwise rotation of Linked List
Last Updated :
12 Jul, 2025
Given a singly linked list and an integer K, the task is to rotate the linked list clockwise to the right by K places.
Examples:
Input: 1 -> 2 -> 3 -> 4 -> 5 -> NULL, K = 2
Output: 4 -> 5 -> 1 -> 2 -> 3 -> NULL
Input: 7 -> 9 -> 11 -> 13 -> 3 -> 5 -> NULL, K = 12
Output: 7 -> 9 -> 11 -> 13 -> 3 -> 5 -> NULL
Approach: To rotate the linked list first check whether the given k is greater than the count of nodes in the linked list or not. Traverse the list and find the length of the linked list then compare it with k, if less then continue otherwise deduce it in the range of linked list size by taking modulo with the length of the list.
After that subtract the value of k from the length of the list. Now, the question has been changed to the left rotation of the linked list so follow that procedure:
- Change the next of the kth node to NULL.
- Change the next of the last node to the previous head node.
- Change the head to (k+1)th node.
In order to do that, the pointers to the kth node, (k+1)th node, and last node are required.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
/* Link list node */
class Node {
public:
int data;
Node* next;
};
/* A utility function to push a node */
void push(Node** head_ref, int new_data)
{
/* allocate node */
Node* new_node = new Node();
/* put in the data */
new_node->data = new_data;
/* link the old list of the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* A utility function to print linked list */
void printList(Node* node)
{
while (node != NULL) {
cout << node->data << " -> ";
node = node->next;
}
cout << "NULL";
}
// Function that rotates the given linked list
// clockwise by k and returns the updated
// head pointer
Node* rightRotate(Node* head, int k)
{
// If the linked list is empty
if (!head)
return head;
// len is used to store length of the linked list
// tmp will point to the last node after this loop
Node* tmp = head;
int len = 1;
while (tmp->next != NULL) {
tmp = tmp->next;
len++;
}
// If k is greater than the size
// of the linked list
if (k > len)
k = k % len;
// Subtract from length to convert
// it into left rotation
k = len - k;
// If no rotation needed then
// return the head node
if (k == 0 || k == len)
return head;
// current will either point to
// kth or NULL after this loop
Node* current = head;
int cnt = 1;
while (cnt < k && current != NULL) {
current = current->next;
cnt++;
}
// If current is NULL then k is equal to the
// count of nodes in the list
// Don't change the list in this case
if (current == NULL)
return head;
// current points to the kth node
Node* kthnode = current;
// Change next of last node to previous head
tmp->next = head;
// Change head to (k+1)th node
head = kthnode->next;
// Change next of kth node to NULL
kthnode->next = NULL;
// Return the updated head pointer
return head;
}
// Driver code
int main()
{
/* The constructed linked list is:
1->2->3->4->5 */
Node* head = NULL;
push(&head, 5);
push(&head, 4);
push(&head, 3);
push(&head, 2);
push(&head, 1);
int k = 2;
// Rotate the linked list
Node* updated_head = rightRotate(head, k);
// Print the rotated linked list
printList(updated_head);
return 0;
}
Java
// Java implementation of the approach
class GFG
{
/* Link list node */
static class Node
{
int data;
Node next;
}
/* A utility function to push a node */
static Node push(Node head_ref, int new_data)
{
/* allocate node */
Node new_node = new Node();
/* put in the data */
new_node.data = new_data;
/* link the old list of the new node */
new_node.next = (head_ref);
/* move the head to point to the new node */
(head_ref) = new_node;
return head_ref;
}
/* A utility function to print linked list */
static void printList(Node node)
{
while (node != null)
{
System.out.print(node.data + " -> ");
node = node.next;
}
System.out.print( "null");
}
// Function that rotates the given linked list
// clockwise by k and returns the updated
// head pointer
static Node rightRotate(Node head, int k)
{
// If the linked list is empty
if (head == null)
return head;
// len is used to store length of the linked list
// tmp will point to the last node after this loop
Node tmp = head;
int len = 1;
while (tmp.next != null)
{
tmp = tmp.next;
len++;
}
// If k is greater than the size
// of the linked list
if (k > len)
k = k % len;
// Subtract from length to convert
// it into left rotation
k = len - k;
// If no rotation needed then
// return the head node
if (k == 0 || k == len)
return head;
// current will either point to
// kth or null after this loop
Node current = head;
int cnt = 1;
while (cnt < k && current != null)
{
current = current.next;
cnt++;
}
// If current is null then k is equal to the
// count of nodes in the list
// Don't change the list in this case
if (current == null)
return head;
// current points to the kth node
Node kthnode = current;
// Change next of last node to previous head
tmp.next = head;
// Change head to (k+1)th node
head = kthnode.next;
// Change next of kth node to null
kthnode.next = null;
// Return the updated head pointer
return head;
}
// Driver code
public static void main(String args[])
{
/* The constructed linked list is:
1.2.3.4.5 */
Node head = null;
head = push(head, 5);
head = push(head, 4);
head = push(head, 3);
head = push(head, 2);
head = push(head, 1);
int k = 2;
// Rotate the linked list
Node updated_head = rightRotate(head, k);
// Print the rotated linked list
printList(updated_head);
}
}
// This code is contributed by Arnub Kundu
Python3
# Python3 implementation of the approach
''' Link list node '''
class Node:
def __init__(self, data):
self.data = data
self.next = None
''' A utility function to push a node '''
def push(head_ref, new_data):
''' allocate node '''
new_node = Node(new_data)
''' put in the data '''
new_node.data = new_data
''' link the old list of the new node '''
new_node.next = (head_ref)
''' move the head to point to the new node '''
(head_ref) = new_node
return head_ref
''' A utility function to print linked list '''
def printList(node):
while (node != None):
print(node.data, end=' -> ')
node = node.next
print("NULL")
# Function that rotates the given linked list
# clockwise by k and returns the updated
# head pointer
def rightRotate(head, k):
# If the linked list is empty
if (not head):
return head
# len is used to store length of the linked list
# tmp will point to the last node after this loop
tmp = head
len = 1
while (tmp.next != None):
tmp = tmp.next
len += 1
# If k is greater than the size
# of the linked list
if (k > len):
k = k % len
# Subtract from length to convert
# it into left rotation
k = len - k
# If no rotation needed then
# return the head node
if (k == 0 or k == len):
return head
# current will either point to
# kth or None after this loop
current = head
cnt = 1
while (cnt < k and current != None):
current = current.next
cnt += 1
# If current is None then k is equal to the
# count of nodes in the list
# Don't change the list in this case
if (current == None):
return head
# current points to the kth node
kthnode = current
# Change next of last node to previous head
tmp.next = head
# Change head to (k+1)th node
head = kthnode.next
# Change next of kth node to None
kthnode.next = None
# Return the updated head pointer
return head
# Driver code
if __name__ == '__main__':
''' The constructed linked list is:
1.2.3.4.5 '''
head = None
head = push(head, 5)
head = push(head, 4)
head = push(head, 3)
head = push(head, 2)
head = push(head, 1)
k = 2
# Rotate the linked list
updated_head = rightRotate(head, k)
# Print the rotated linked list
printList(updated_head)
# This code is contributed by rutvik_56
C#
// C# implementation of the approach
using System;
class GFG
{
/* Link list node */
public class Node
{
public int data;
public Node next;
}
/* A utility function to push a node */
static Node push(Node head_ref,
int new_data)
{
/* allocate node */
Node new_node = new Node();
/* put in the data */
new_node.data = new_data;
/* link the old list of the new node */
new_node.next = (head_ref);
/* move the head to point
to the new node */
(head_ref) = new_node;
return head_ref;
}
/* A utility function to print linked list */
static void printList(Node node)
{
while (node != null)
{
Console.Write(node.data + " -> ");
node = node.next;
}
Console.Write("null");
}
// Function that rotates the given linked list
// clockwise by k and returns the updated
// head pointer
static Node rightRotate(Node head, int k)
{
// If the linked list is empty
if (head == null)
return head;
// len is used to store length of
// the linked list, tmp will point
// to the last node after this loop
Node tmp = head;
int len = 1;
while (tmp.next != null)
{
tmp = tmp.next;
len++;
}
// If k is greater than the size
// of the linked list
if (k > len)
k = k % len;
// Subtract from length to convert
// it into left rotation
k = len - k;
// If no rotation needed then
// return the head node
if (k == 0 || k == len)
return head;
// current will either point to
// kth or null after this loop
Node current = head;
int cnt = 1;
while (cnt < k && current != null)
{
current = current.next;
cnt++;
}
// If current is null then k is equal
// to the count of nodes in the list
// Don't change the list in this case
if (current == null)
return head;
// current points to the kth node
Node kthnode = current;
// Change next of last node
// to previous head
tmp.next = head;
// Change head to (k+1)th node
head = kthnode.next;
// Change next of kth node to null
kthnode.next = null;
// Return the updated head pointer
return head;
}
// Driver code
public static void Main(String []args)
{
/* The constructed linked list is:
1.2.3.4.5 */
Node head = null;
head = push(head, 5);
head = push(head, 4);
head = push(head, 3);
head = push(head, 2);
head = push(head, 1);
int k = 2;
// Rotate the linked list
Node updated_head = rightRotate(head, k);
// Print the rotated linked list
printList(updated_head);
}
}
// This code is contributed by PrinciRaj1992
JavaScript
<script>
// JavaScript implementation of the approach
/* Link list node */
class Node {
constructor() {
this.data = 0;
this.next = null;
}
}
/* A utility function to push a node */
function push(head_ref , new_data) {
/* allocate node */
var new_node = new Node();
/* put in the data */
new_node.data = new_data;
/* link the old list of the new node */
new_node.next = (head_ref);
/* move the head to point to the new node */
(head_ref) = new_node;
return head_ref;
}
/* A utility function to print linked list */
function printList(node) {
while (node != null) {
document.write(node.data + " -> ");
node = node.next;
}
document.write("null");
}
// Function that rotates the given linked list
// clockwise by k and returns the updated
// head pointer
function rightRotate(head , k) {
// If the linked list is empty
if (head == null)
return head;
// len is used to store length
// of the linked list
// tmp will point to the last
// node after this loop
var tmp = head;
var len = 1;
while (tmp.next != null) {
tmp = tmp.next;
len++;
}
// If k is greater than the size
// of the linked list
if (k > len)
k = k % len;
// Subtract from length to convert
// it into left rotation
k = len - k;
// If no rotation needed then
// return the head node
if (k == 0 || k == len)
return head;
// current will either point to
// kth or null after this loop
var current = head;
var cnt = 1;
while (cnt < k && current != null) {
current = current.next;
cnt++;
}
// If current is null then k is equal to the
// count of nodes in the list
// Don't change the list in this case
if (current == null)
return head;
// current points to the kth node
var kthnode = current;
// Change next of last node to previous head
tmp.next = head;
// Change head to (k+1)th node
head = kthnode.next;
// Change next of kth node to null
kthnode.next = null;
// Return the updated head pointer
return head;
}
// Driver code
/*
* The constructed linked list is: 1.2.3.4.5
*/
var head = null;
head = push(head, 5);
head = push(head, 4);
head = push(head, 3);
head = push(head, 2);
head = push(head, 1);
var k = 2;
// Rotate the linked list
var updated_head = rightRotate(head, k);
// Print the rotated linked list
printList(updated_head);
// This code contributed by Rajput-Ji
</script>
Output: 4 -> 5 -> 1 -> 2 -> 3 -> NULL
Time Complexity: O(n) where n is the number of nodes in Linked List.
Auxiliary Space: O(1)
STL based approach :
This problem can also be solved using the deque data structure provided in the C++ STL
Approach :
Initialise a deque with the type Node* and push the linked list into it.Then keep popping from it's back and adding that node to it's front until the number of operations are not equal to k.
C++
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int val;
Node* next;
Node(int d)
{
val = d;
next = NULL;
}
};
void build(Node*& head, int val)
{
if (head == NULL) {
head = new Node(val);
}
else {
Node* temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = new Node(val);
}
}
Node* rotate_clockwise(Node* head, int k)
{
if (head == NULL) {
return NULL;
}
deque<Node*> q;
Node* temp = head;
while (temp != NULL) {
q.push_back(temp);
temp = temp->next;
}
k %= q.size();
while (
k--) // popping from back and adding to it's front
{
q.back()->next = q.front();
q.push_front(q.back());
q.pop_back();
q.back()->next = NULL;
}
return q.front();
}
void print(Node* head)
{
while (head != NULL) {
cout << head->val << " -> ";
head = head->next;
}
cout << "NULL";
cout << endl;
}
int main()
{
Node* head = NULL;
build(head, 1);
build(head, 2);
build(head, 3);
build(head, 4);
build(head, 5);
int k = 2;
Node* r = rotate_clockwise(head, k);
print(r);
return 0;
}
Python3
# Python Program for rotating a Linked List by k
from collections import deque
class Node:
def __init__(self, data):
self.data = data
self.next = None
def build(head, val):
if(head == None):
head = Node(val)
else:
temp = head
while(temp.next != None):
temp = temp.next
temp.next = Node(val)
return head
def printList(node):
while(node != None):
print(node.data, end = "->")
node = node.next
print("NULL")
def rotate_clockwise(head, k):
if(head == None):
return None
q = deque([])
temp = head
while(temp != None):
q.append(temp)
temp = temp.next
k %= len(q)
while(k != 0):
q[-1].next = q[0]
q.appendleft(q[-1])
q.pop()
q[-1].next = None
k = k-1
return q[0]
head = None
head = build(head, 1)
head = build(head, 2)
head = build(head, 3)
head = build(head, 4)
head = build(head, 5)
k = 2
r = rotate_clockwise(head, k)
printList(r)
# This code is contributed by Yash Agarwal(yashagarwal2852002)
C#
// C# program for the above approach
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
// class containing left and right
// child of current node and key value
public class Node{
public int val;
public Node next;
public Node(int d){
val = d;
next = null;
}
}
public class llist{
Node head;
public void build(int val){
if(head == null){
head = new Node(val);
}
else{
Node temp = head;
while(temp.next != null){
temp = temp.next;
}
temp.next = new Node(val);
}
}
public Node rotate_clockwise(int k){
if(head == null) return null;
LinkedList<Node> q = new LinkedList<Node>();
Node temp = head;
while(temp != null){
q.AddLast(temp);
temp = temp.next;
}
k %= q.Count;
while(k > 0) // popping from back and adding to it's front
{
k--;
q.Last.Value.next = q.First.Value;
q.AddFirst(q.Last.Value);
q.RemoveLast();
q.Last.Value.next = null;
}
return q.First.Value;
}
public void print(Node head){
while(head != null){
Console.Write(head.val + " -> ");
head = head.next;
}
Console.Write("NULL");
Console.Write("\n");
}
public static void Main(String[] args){
llist list = new llist();
list.build(1);
list.build(2);
list.build(3);
list.build(4);
list.build(5);
int k = 2;
Node r = list.rotate_clockwise(k);
list.print(r);
}
}
// this code is contributed by Kirti Agarwal(kirtiagarwal23121999)
JavaScript
// JavaScript Program for the above approach
class Node{
constructor(d){
this.val = d;
this.next = null;
}
}
function build(head, val){
if(head == null){
head = new Node(val);
}
else{
let temp = head;
while(temp.next != null){
temp = temp.next;
}
temp.next = new Node(val);
}
return head;
}
function rotate_clockwise(head, k){
if(head == null) return null;
let q = [];
let temp = head;
while(temp != null){
q.push(temp);
temp = temp.next;
}
k %= q.length;
while(k--) // popping from back and adding to it's front
{
q[q.length-1].next = q[0];
q.unshift(q[q.length-1]);
q.pop();
q[q.length-1].next = null;
}
return q[0];
}
function print(head){
while(head != null){
console.log(head.val + " -> ");
head = head.next;
}
console.log("NULL");
}
let head = null;
head = build(head, 1);
head = build(head, 2);
head = build(head, 3);
head = build(head, 4);
head = build(head, 5);
let k = 2;
let r = rotate_clockwise(head, k);
print(r);
// This code contributed by Yash Agarwal(yashagawal2852002)
Java
import java.util.*;
class Node {
public int val;
public Node next;
public Node(int d) {
val = d;
next = null;
}
}
class GFG {
public static Node build(Node head, int data) {
Node new_node = new Node(data);
if (head == null) {
head = new_node;
} else {
Node last = head;
while (last.next != null) {
last = last.next;
}
last.next = new_node;
}
return head;
}
public static Node rotate_clockwise(Node head, int k) {
if (head == null) {
return null;
}
Deque < Node > q = new LinkedList < > ();
Node temp = head;
while (temp != null) {
q.add(temp);
temp = temp.next;
}
k %= q.size();
while (k-- > 0) {
q.peekLast().next = q.peekFirst();
q.offerFirst(q.pollLast());
q.peekLast().next = null;
}
return q.peekFirst();
}
public static void print(Node head) {
while (head != null) {
System.out.print(head.val + " -> ");
head = head.next;
}
System.out.print("NULL");
System.out.println();
}
public static void main(String[] args) {
Node head = null;
head = build(head, 1);
head = build(head, 2);
head = build(head, 3);
head = build(head, 4);
head = build(head, 5);
int k = 2;
Node r = rotate_clockwise(head, k);
print(r);
}
}
Output4 -> 5 -> 1 -> 2 -> 3 -> NULL
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem