C++ Program For Rotating A Linked List
Last Updated :
23 Jul, 2025
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 :
C++
// C++ program to rotate a
// linked list counter clock wise
#include <bits/stdc++.h>
using namespace std;
// Link list node
class Node
{
public:
int data;
Node* next;
};
// This function rotates a linked list
// counter-clockwise and updates the
// head. The function assumes that k is
// smaller than size of linked list.
// It doesn't modify the list if
// k is greater than or equal to size
void rotate(Node** head_ref, int k)
{
if (k == 0)
return;
// Let us understand the below
// code for example k = 4 and
// list = 10->20->30->40->50->60.
Node* current = *head_ref;
// current will either point to
// kth or NULL after this loop.
// current will point to node
// 40 in the above example
int count = 1;
while (count < k &&
current != NULL)
{
current = current->next;
count++;
}
// If current is NULL, k is greater
// than or equal to count of nodes
// in linked list. Don't change the
// list in this case
if (current == NULL)
return;
// current points to kth node.
// Store it in a variable. kthNode
// points to node 40 in the above
// example
Node* kthNode = current;
// current will point to
// last node after this loop
// current will point to
// node 60 in the above example
while (current->next != NULL)
current = current->next;
// Change next of last node to
// previous head. Next of 60 is
// now changed to node 10
current->next = *head_ref;
// Change head to (k+1)th node
// head is now changed to node 50
*head_ref = kthNode->next;
// Change next of kth node to NULL
// next of 40 is now NULL
kthNode->next = NULL;
}
// UTILITY FUNCTIONS
// 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;
}
// Function to print linked list
void printList(Node* node)
{
while (node != NULL)
{
cout << node->data << " ";
node = node->next;
}
}
// Driver code
int main(void)
{
// Start with the empty list
Node* head = NULL;
// Create a list
// 10->20->30->40->50->60
for (int i = 60; i > 0; i -= 10)
push(&head, i);
cout << "Given linked list ";
printList(head);
rotate(&head, 4);
cout << "Rotated Linked list ";
printList(head);
return (0);
}
// This code is contributed by rathbhupendra
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)
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.
C++
// C++ program to rotate a
// linked list counter clock wise
#include <bits/stdc++.h>
using namespace std;
// Link list node
class Node
{
public:
int data;
Node* next;
};
// This function rotates a linked list
// counter-clockwise and updates the
// head. The function assumes that k is
// smaller than size of linked list.
void rotate(Node** head_ref, int k)
{
if (k == 0)
return;
// Let us understand the below
// code for example k = 4 and
// list = 10->20->30->40->50->60.
Node* current = *head_ref;
// Traverse till the end.
while (current->next != NULL)
current = current->next;
current->next = *head_ref;
current = *head_ref;
// Traverse the linked list to
// k-1 position which will be
// last element for rotated array.
for (int i = 0; i < k - 1; i++)
current = current->next;
// Update the head_ref and last
// element pointer to NULL
*head_ref = current->next;
current->next = NULL;
}
// UTILITY FUNCTIONS
// 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;
}
// Function to print linked list
void printList(Node* node)
{
while (node != NULL)
{
cout << node->data << " ";
node = node->next;
}
}
// Driver code
int main(void)
{
// Start with the empty list
Node* head = NULL;
// Create a list
// 10->20->30->40->50->60
for (int i = 60; i > 0; i -= 10)
push(&head, i);
cout << "Given linked list ";
printList(head);
rotate(&head, 4);
cout << "Rotated Linked list ";
printList(head);
return (0);
}
// This code is contributed by pkurada
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 given Linked List.
Auxiliary Space: O(1)
Please refer complete article on Rotate a Linked List for more details!
Similar Reads
C++ Programming Language C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to
5 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Object Oriented Programming in C++ Object Oriented Programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so th
5 min read
Second Largest Element in an Array Given an array of positive integers arr[] of size n, the task is to find second largest distinct element in the array.Note: If the second largest element does not exist, return -1. Examples:Input: arr[] = [12, 35, 1, 10, 34, 1]Output: 34Explanation: The largest element of the array is 35 and the sec
14 min read
Maximum Subarray Sum - Kadane's Algorithm Given an integer array arr[], find the subarray (containing at least one element) which has the maximum possible sum, and return that sum.Note: A subarray is a continuous part of an array.Examples:Input: arr[] = [2, 3, -8, 7, -1, 2, 3]Output: 11Explanation: The subarray [7, -1, 2, 3] has the largest
8 min read
0/1 Knapsack Problem Given n items where each item has some weight and profit associated with it and also given a bag with capacity W, [i.e., the bag can hold at most W weight in it]. The task is to put the items into the bag such that the sum of profits associated with them is the maximum possible. Note: The constraint
15+ min read
Vector in C++ STL C++ vector is a dynamic array that stores collection of elements same type in contiguous memory. It has the ability to resize itself automatically when an element is inserted or deleted.Create a VectorBefore creating a vector, we must know that a vector is defined as the std::vector class template i
7 min read
Inheritance in C++ The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object-Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the informatio
10 min read
Two Sum - Pair with given Sum Given an array arr[] of n integers and a target value, check if there exists a pair whose sum equals the target. This is a variation of the 2Sum problem.Examples: Input: arr[] = [0, -1, 2, -3, 1], target = -2Output: trueExplanation: There is a pair (1, -3) with the sum equal to given target, 1 + (-3
15+ min read
C++ Interview Questions and Answers (2025) C++ - the must-known and all-time favourite programming language of coders. It is still relevant as it was in the mid-80s. As a general-purpose and object-oriented programming language is extensively employed mostly every time during coding. As a result, some job roles demand individuals be fluent i
15+ min read