Given a singly linked list and an integer k, the task is to rotate the linked list to the left by k places.
Examples:
Input: linked list = 10 -> 20 -> 30 -> 40 -> 50, k = 4
Output: 50 -> 10 -> 20 -> 30 -> 40
Explanation: After rotating the linked list to the left by 4 places, the 5th node, i.e node 50 becomes the head of the linked list and next pointer of node 50 points to node 10.
Input: linked list = 10 -> 20 -> 30 -> 40, k = 6
Output: 30 -> 40 -> 10 -> 20
Explanation: After rotating the linked list to the left by 6 places (same as rotating by 2 places as (k % len) = (6 % 4 = 2)) , the 3rd node, i.e node 30 becomes the head of the linked list and next pointer of node 40 points to node 10.
[Naive Approach] Shifting head node to the end k times - O(n * k) Time and O(1) Space
To rotate a linked list to the left k places, we can repeatedly move the head node to the end of the linked list k times.
C++
// C++ program to rotate a linked list by
// changing moving first node to end k times
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node *next;
Node(int new_data) {
data = new_data;
next = nullptr;
}
};
// Function to rotate the linked list
// left by k nodes
Node *rotate(Node *head, int k) {
if (k == 0 || head == nullptr)
return head;
// Rotate the list by k nodes
for (int i = 0; i < k; ++i) {
Node *curr = head;
while (curr->next != nullptr)
curr = curr->next;
// Move the first node to the last
curr->next = head;
curr = curr->next;
head = head->next;
curr->next = nullptr;
}
return head;
}
void printList(Node *node) {
while (node != nullptr) {
cout << node->data << " ";
node = node->next;
}
cout << endl;
}
int main() {
// Create a hard-coded linked list:
// 10 -> 20 -> 30 -> 40
Node *head = new Node(10);
head->next = new Node(20);
head->next->next = new Node(30);
head->next->next->next = new Node(40);
head = rotate(head, 6);
printList(head);
return 0;
}
C
// C program to rotate a linked list
// by changing moving first node to end k times.
#include <stdio.h>
#include <stdlib.h>
// A linked list node
struct Node {
int data;
struct Node* next;
};
// Function to create a new node
struct Node* createNode(int new_data) {
struct Node* new_node =
(struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = NULL;
return new_node;
}
// Function to rotate the linked list
// left by k nodes
struct Node* rotate(struct Node *head, int k) {
if (k == 0 || head == NULL)
return head;
// Rotate the list by k nodes
for (int i = 0; i < k; ++i) {
struct Node *curr = head;
while (curr->next != NULL)
curr = curr->next;
// Move the first node to the last
curr->next = head;
curr = curr->next;
head = head->next;
curr->next = NULL;
}
return head;
}
void printList(struct Node *node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
printf("\n");
}
int main() {
// Create a hard-coded linked list:
// 10 -> 20 -> 30 -> 40
struct Node *head = createNode(10);
head->next = createNode(20);
head->next->next = createNode(30);
head->next->next->next = createNode(40);
head = rotate(head, 6);
printList(head);
return 0;
}
Java
// Java program to rotate a linked list
// by changing moving first node to end k times.
class Node {
int data;
Node next;
Node(int new_data) {
data = new_data;
next = null;
}
}
class GfG {
// Function to rotate the linked list
// left by k nodes
static Node rotate(Node head, int k) {
if (k == 0 || head == null)
return head;
// Rotate the list by k nodes
for (int i = 0; i < k; ++i) {
Node curr = head;
while (curr.next != null)
curr = curr.next;
// Move the first node to the last
curr.next = head;
curr = curr.next;
head = head.next;
curr.next = null;
}
return head;
}
static void printList(Node node) {
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
System.out.println();
}
public static void main(String[] args) {
// Create a hard-coded linked list:
// 10 -> 20 -> 30 -> 40
Node head = new Node(10);
head.next = new Node(20);
head.next.next = new Node(30);
head.next.next.next = new Node(40);
head = rotate(head, 6);
printList(head);
}
}
Python
# Python program to rotate a linked list
# by changing moving first node to end k times.
class Node:
def __init__(self, newData):
self.data = newData
self.next = None
# Function to rotate the linked list
# left by k nodes
def rotate(head, k):
if k == 0 or head is None:
return head
# Rotate the list by k nodes
for _ in range(k):
curr = head
while curr.next is not None:
curr = curr.next
# Move the first node to the last
curr.next = head
curr = curr.next
head = head.next
curr.next = None
return head
def printList(node):
while node is not None:
print(node.data, end=" ")
node = node.next
print()
if __name__ == "__main__":
# Create a hard-coded linked list:
# 10 -> 20 -> 30 -> 40
head = Node(10)
head.next = Node(20)
head.next.next = Node(30)
head.next.next.next = Node(40)
head = rotate(head, 6)
printList(head)
C#
// C# program to rotate a linked list
// by changing moving first node to end k times
using System;
class Node {
public int data;
public Node next;
public Node(int new_data) {
data = new_data;
next = null;
}
}
// Function to rotate the linked list
// left by k nodes
class GfG {
static Node Rotate(Node head, int k) {
if (k == 0 || head == null)
return head;
// Rotate the list by k nodes
for (int i = 0; i < k; ++i) {
Node curr = head;
while (curr.next != null)
curr = curr.next;
// Move the first node to the last
curr.next = head;
curr = curr.next;
head = head.next;
curr.next = null;
}
return head;
}
static void PrintList(Node node) {
while (node != null) {
Console.Write(node.data + " ");
node = node.next;
}
Console.WriteLine();
}
static void Main() {
// Create a hard-coded linked list:
// 10 -> 20 -> 30 -> 40
Node head = new Node(10);
head.next = new Node(20);
head.next.next = new Node(30);
head.next.next.next = new Node(40);
head = Rotate(head, 6);
PrintList(head);
}
}
JavaScript
// Javascript program to rotate a linked list
// by changing moving first node to end k times.
class Node {
constructor(new_data) {
this.data = new_data;
this.next = null;
}
}
// Function to rotate the linked list
// left by k nodes
function rotate(head, k) {
if (k === 0 || head === null) {
return head;
}
// Rotate the list by k nodes
for (let i = 0; i < k; ++i) {
let curr = head;
while (curr.next !== null) {
curr = curr.next;
}
// Move the first node to the last
curr.next = head;
curr = curr.next;
head = head.next;
curr.next = null;
}
return head;
}
function printList(node) {
let result = '';
while (node !== null) {
result += node.data + ' ';
node = node.next;
}
console.log(result.trim());
}
// Create a hard-coded linked list:
// 10 -> 20 -> 30 -> 40
let head = new Node(10);
head.next = new Node(20);
head.next.next = new Node(30);
head.next.next.next = new Node(40);
head = rotate(head, 6);
printList(head);
Time Complexity: O(n * k), where n is the number of nodes in Linked List and k is the number of rotations.
Auxiliary Space: O(1)
[Expected Approach] By changing pointer of kth node - O(n) Time and O(1) Space
The idea is to first convert the linked list to circular linked list by updating the next pointer of last node to the head of linked list. Then, traverse to the kth node and update the head of the linked list to the (k+1)th node. Finally, break the loop by updating the next pointer of kth node to NULL..
How to handle large values of k?
For a linked list of size n, if we rotate the linked list to the left by n places, then the linked list will remain unchanged and if we rotate the list to the left by (n + 1) places, then it is same as rotating the linked list to the left by 1 place. Similarly, if we rotate the linked list k (k >= n) places to the left, then it is same as rotating the linked list by (k % n) places. So, we can simply update k with k % n to handle large values of k.
Working:
Below is the implementation of the above algorithm:
C++
// C++ program to rotate a linked list
// by changing pointer of kth node
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node *next;
Node(int new_data) {
data = new_data;
next = nullptr;
}
};
// Function to rotate the linked list
// to the left by k places
Node *rotate(Node *head, int k) {
// If the linked list is empty or no rotations are
// needed, then return the original linked list
if (k == 0 || head == nullptr)
return head;
Node *curr = head;
int len = 1;
// Find the length of linked list
while (curr->next != nullptr) {
curr = curr->next;
len += 1;
}
// Modulo k with length of linked list to handle
// large values of k
k %= len;
if (k == 0)
return head;
// Make the linked list circular
curr->next = head;
// Traverse the linked list to find the kth node
curr = head;
for (int i = 1; i < k; i++)
curr = curr->next;
// Update the (k + 1)th node as the new head
head = curr->next;
// Break the loop by updating next pointer of kth node
curr->next = nullptr;
return head;
}
void printList(Node *node) {
while (node != nullptr) {
cout << node->data << " ";
node = node->next;
}
cout << endl;
}
int main() {
// Create a hard-coded linked list:
// 10 -> 20 -> 30 -> 40
Node *head = new Node(10);
head->next = new Node(20);
head->next->next = new Node(30);
head->next->next->next = new Node(40);
head = rotate(head, 6);
printList(head);
return 0;
}
C
// C program to rotate a linked list
// by changing pointer of kth node
#include <stdio.h>
struct Node {
int data;
struct Node *next;
};
// Function to create a new node
struct Node* createNode(int new_data) {
struct Node *new_node =
(struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = NULL;
return new_node;
}
// Function to rotate the linked list
// to the left by k places
struct Node* rotate(struct Node *head, int k) {
// If the linked list is empty or no rotations are
// needed, then return the original linked list
if (k == 0 || head == NULL)
return head;
struct Node *curr = head;
int len = 1;
// Find the length of linked list
while (curr->next != NULL) {
curr = curr->next;
len += 1;
}
// Modulo k with length of linked list to handle
// large values of k
k %= len;
if (k == 0)
return head;
// Make the linked list circular
curr->next = head;
// Traverse the linked list to find the kth node
curr = head;
for (int i = 1; i < k; i++)
curr = curr->next;
// Update the (k + 1)th node as the new head
head = curr->next;
// Break the loop by updating next pointer of kth node
curr->next = NULL;
return head;
}
void printList(struct Node *node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
printf("\n");
}
int main() {
// Create a hard-coded linked list:
// 10 -> 20 -> 30 -> 40
struct Node *head = createNode(10);
head->next = createNode(20);
head->next->next = createNode(30);
head->next->next->next = createNode(40);
head = rotate(head, 6);
printList(head);
return 0;
}
Java
// Java program to rotate a linked list
// by changing pointer of kth node
class Node {
int data;
Node next;
Node(int new_data) {
data = new_data;
next = null;
}
}
// Function to rotate the linked list
// to the left by k places
class GfG {
static Node rotate(Node head, int k) {
// If the linked list is empty or no rotations are
// needed, then return the original linked list
if (k == 0 || head == null)
return head;
Node curr = head;
int len = 1;
// Find the length of linked list
while (curr.next != null) {
curr = curr.next;
len += 1;
}
// Modulo k with length of linked list to handle
// large values of k
k %= len;
if (k == 0)
return head;
// Make the linked list circular
curr.next = head;
// Traverse the linked list to find the kth node
curr = head;
for (int i = 1; i < k; i++)
curr = curr.next;
// Update the (k + 1)th node as the new head
head = curr.next;
// Break the loop by updating next pointer of kth node
curr.next = null;
return head;
}
static void printList(Node node) {
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
System.out.println();
}
public static void main(String[] args) {
// Create a hard-coded linked list:
// 10 -> 20 -> 30 -> 40
Node head = new Node(10);
head.next = new Node(20);
head.next.next = new Node(30);
head.next.next.next = new Node(40);
head = rotate(head, 6);
printList(head);
}
}
Python
# Python program to rotate a linked list
# by changing pointer of kth node
class Node:
def __init__(self, newData):
self.data = newData
self.next = None
# Function to rotate the linked list to the left by k places
def rotate(head, k):
# If the linked list is empty or no rotations are needed,
# return the original linked list
if k == 0 or head is None:
return head
curr = head
length = 1
# Find the length of the linked list
while curr.next is not None:
curr = curr.next
length += 1
# Modulo k with length of linked list to handle
# large values of k
k %= length
if k == 0:
curr.next = None
return head
# Make the linked list circular
curr.next = head
# Traverse the linked list to find the kth node
curr = head
for _ in range(1, k):
curr = curr.next
# Update the (k + 1)th node as the new head
newHead = curr.next
# Break the loop by updating the next pointer
# of kth node
curr.next = None
return newHead
def printList(node):
while node is not None:
print(node.data, end=" ")
node = node.next
print()
if __name__ == "__main__":
# Create a hard-coded linked list: 10 -> 20 -> 30 -> 40
head = Node(10)
head.next = Node(20)
head.next.next = Node(30)
head.next.next.next = Node(40)
head = rotate(head, 6)
printList(head)
C#
// C program to rotate a linked list
// by changing pointer of kth node
using System;
public class Node {
public int data;
public Node next;
public Node(int new_data) {
data = new_data;
next = null;
}
}
// Function to rotate the linked list
// to the left by k places
class GfG {
static Node Rotate(Node head, int k) {
// If the linked list is empty or no rotations are
// needed, then return the original linked list
if (k == 0 || head == null)
return head;
Node curr = head;
int len = 1;
// Find the length of linked list
while (curr.next != null) {
curr = curr.next;
len += 1;
}
// Modulo k with length of linked list to handle
// large values of k
k %= len;
if (k == 0)
return head;
// Make the linked list circular
curr.next = head;
// Traverse the linked list to find the kth node
curr = head;
for (int i = 1; i < k; i++)
curr = curr.next;
// Update the (k + 1)th node as the new head
Node newHead = curr.next;
// Break the loop by updating next pointer of kth node
curr.next = null;
return newHead;
}
static void PrintList(Node node) {
while (node != null) {
Console.Write(node.data + " ");
node = node.next;
}
Console.WriteLine();
}
public static void Main() {
// Create a hard-coded linked list:
// 10 -> 20 -> 30 -> 40
Node head = new Node(10);
head.next = new Node(20);
head.next.next = new Node(30);
head.next.next.next = new Node(40);
head = Rotate(head, 6);
PrintList(head);
}
}
JavaScript
// JavaScript program to rotate a linked list
// by changing pointer of kth node
class Node {
constructor(new_data) {
this.data = new_data;
this.next = null;
}
}
// Function to rotate the linked list
// to the left by k places
function rotate(head, k) {
// If the linked list is empty or no rotations are
// needed, then return the original linked list
if (k === 0 || head === null)
return head;
let curr = head;
let len = 1;
// Find the length of linked list
while (curr.next !== null) {
curr = curr.next;
len += 1;
}
// Modulo k with length of linked list to handle
// large values of k
k %= len;
if (k === 0) {
curr.next = null;
return head;
}
// Make the linked list circular
curr.next = head;
// Traverse the linked list to find the kth node
curr = head;
for (let i = 1; i < k; i++)
curr = curr.next;
// Update the (k + 1)th node as the new head
let newHead = curr.next;
// Break the loop by updating next pointer of kth node
curr.next = null;
return newHead;
}
function printList(node) {
let output = '';
while (node !== null) {
output += node.data + ' ';
node = node.next;
}
console.log(output.trim());
}
// Create a hard-coded linked list:
// 10 -> 20 -> 30 -> 40
let head = new Node(10);
head.next = new Node(20);
head.next.next = new Node(30);
head.next.next.next = new Node(40);
head = rotate(head, 6);
printList(head);
Time Complexity: O(n), where n is the number of nodes in linked list.
Auxiliary Space: O(1)
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