VOOZH about

URL: https://www.geeksforgeeks.org/dsa/rotate-a-linked-list/

⇱ Rotate a Linked List - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Rotate a Linked List

Last Updated : 29 Aug, 2025

Given the head of a singly linked list and an integer k, rotate the list to the left by k positions and return the updated head.

Examples:

Input: k = 4

👁 1

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.

👁 2


Input: k = 6

👁 3

Output: 30 -> 40 -> 10 -> 20 
Explanation: After rotating the list left by 6 positions, the node with value 30 becomes the new head, and the node with value 40 points to the node with value 10.

👁 4

[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.


Output
30 -> 40 -> 10 -> 20

[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.

Illustrations:



Output
30 -> 40 -> 10 -> 20 
Comment