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.
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>usingnamespacestd;classNode{public:intdata;Node*next;Node(intnew_data){data=new_data;next=nullptr;}};// Function to rotate the linked list// left by k nodesNode*rotate(Node*head,intk){if(k==0||head==nullptr)returnhead;// Rotate the list by k nodesfor(inti=0;i<k;++i){Node*curr=head;while(curr->next!=nullptr)curr=curr->next;// Move the first node to the lastcurr->next=head;curr=curr->next;head=head->next;curr->next=nullptr;}returnhead;}voidprintList(Node*node){while(node!=nullptr){cout<<node->data<<" ";node=node->next;}cout<<endl;}intmain(){// Create a hard-coded linked list:// 10 -> 20 -> 30 -> 40Node*head=newNode(10);head->next=newNode(20);head->next->next=newNode(30);head->next->next->next=newNode(40);head=rotate(head,6);printList(head);return0;}
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 nodestructNode{intdata;structNode*next;};// Function to create a new nodestructNode*createNode(intnew_data){structNode*new_node=(structNode*)malloc(sizeof(structNode));new_node->data=new_data;new_node->next=NULL;returnnew_node;}// Function to rotate the linked list// left by k nodesstructNode*rotate(structNode*head,intk){if(k==0||head==NULL)returnhead;// Rotate the list by k nodesfor(inti=0;i<k;++i){structNode*curr=head;while(curr->next!=NULL)curr=curr->next;// Move the first node to the lastcurr->next=head;curr=curr->next;head=head->next;curr->next=NULL;}returnhead;}voidprintList(structNode*node){while(node!=NULL){printf("%d ",node->data);node=node->next;}printf("\n");}intmain(){// Create a hard-coded linked list:// 10 -> 20 -> 30 -> 40structNode*head=createNode(10);head->next=createNode(20);head->next->next=createNode(30);head->next->next->next=createNode(40);head=rotate(head,6);printList(head);return0;}
Java
// Java program to rotate a linked list// by changing moving first node to end k times.classNode{intdata;Nodenext;Node(intnew_data){data=new_data;next=null;}}classGfG{// Function to rotate the linked list// left by k nodesstaticNoderotate(Nodehead,intk){if(k==0||head==null)returnhead;// Rotate the list by k nodesfor(inti=0;i<k;++i){Nodecurr=head;while(curr.next!=null)curr=curr.next;// Move the first node to the lastcurr.next=head;curr=curr.next;head=head.next;curr.next=null;}returnhead;}staticvoidprintList(Nodenode){while(node!=null){System.out.print(node.data+" ");node=node.next;}System.out.println();}publicstaticvoidmain(String[]args){// Create a hard-coded linked list:// 10 -> 20 -> 30 -> 40Nodehead=newNode(10);head.next=newNode(20);head.next.next=newNode(30);head.next.next.next=newNode(40);head=rotate(head,6);printList(head);}}
Python
# Python program to rotate a linked list# by changing moving first node to end k times.classNode:def__init__(self,newData):self.data=newDataself.next=None# Function to rotate the linked list# left by k nodesdefrotate(head,k):ifk==0orheadisNone:returnhead# Rotate the list by k nodesfor_inrange(k):curr=headwhilecurr.nextisnotNone:curr=curr.next# Move the first node to the lastcurr.next=headcurr=curr.nexthead=head.nextcurr.next=NonereturnheaddefprintList(node):whilenodeisnotNone:print(node.data,end=" ")node=node.nextprint()if__name__=="__main__":# Create a hard-coded linked list:# 10 -> 20 -> 30 -> 40head=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 timesusingSystem;classNode{publicintdata;publicNodenext;publicNode(intnew_data){data=new_data;next=null;}}// Function to rotate the linked list// left by k nodesclassGfG{staticNodeRotate(Nodehead,intk){if(k==0||head==null)returnhead;// Rotate the list by k nodesfor(inti=0;i<k;++i){Nodecurr=head;while(curr.next!=null)curr=curr.next;// Move the first node to the lastcurr.next=head;curr=curr.next;head=head.next;curr.next=null;}returnhead;}staticvoidPrintList(Nodenode){while(node!=null){Console.Write(node.data+" ");node=node.next;}Console.WriteLine();}staticvoidMain(){// Create a hard-coded linked list:// 10 -> 20 -> 30 -> 40Nodehead=newNode(10);head.next=newNode(20);head.next.next=newNode(30);head.next.next.next=newNode(40);head=Rotate(head,6);PrintList(head);}}
JavaScript
// Javascript program to rotate a linked list// by changing moving first node to end k times.classNode{constructor(new_data){this.data=new_data;this.next=null;}}// Function to rotate the linked list// left by k nodesfunctionrotate(head,k){if(k===0||head===null){returnhead;}// Rotate the list by k nodesfor(leti=0;i<k;++i){letcurr=head;while(curr.next!==null){curr=curr.next;}// Move the first node to the lastcurr.next=head;curr=curr.next;head=head.next;curr.next=null;}returnhead;}functionprintList(node){letresult='';while(node!==null){result+=node.data+' ';node=node.next;}console.log(result.trim());}// Create a hard-coded linked list:// 10 -> 20 -> 30 -> 40lethead=newNode(10);head.next=newNode(20);head.next.next=newNode(30);head.next.next.next=newNode(40);head=rotate(head,6);printList(head);
Output
30 40 10 20
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>usingnamespacestd;classNode{public:intdata;Node*next;Node(intnew_data){data=new_data;next=nullptr;}};// Function to rotate the linked list// to the left by k placesNode*rotate(Node*head,intk){// If the linked list is empty or no rotations are// needed, then return the original linked listif(k==0||head==nullptr)returnhead;Node*curr=head;intlen=1;// Find the length of linked listwhile(curr->next!=nullptr){curr=curr->next;len+=1;}// Modulo k with length of linked list to handle// large values of kk%=len;if(k==0)returnhead;// Make the linked list circularcurr->next=head;// Traverse the linked list to find the kth nodecurr=head;for(inti=1;i<k;i++)curr=curr->next;// Update the (k + 1)th node as the new headhead=curr->next;// Break the loop by updating next pointer of kth nodecurr->next=nullptr;returnhead;}voidprintList(Node*node){while(node!=nullptr){cout<<node->data<<" ";node=node->next;}cout<<endl;}intmain(){// Create a hard-coded linked list:// 10 -> 20 -> 30 -> 40Node*head=newNode(10);head->next=newNode(20);head->next->next=newNode(30);head->next->next->next=newNode(40);head=rotate(head,6);printList(head);return0;}
C
// C program to rotate a linked list// by changing pointer of kth node#include<stdio.h>structNode{intdata;structNode*next;};// Function to create a new nodestructNode*createNode(intnew_data){structNode*new_node=(structNode*)malloc(sizeof(structNode));new_node->data=new_data;new_node->next=NULL;returnnew_node;}// Function to rotate the linked list// to the left by k placesstructNode*rotate(structNode*head,intk){// If the linked list is empty or no rotations are// needed, then return the original linked listif(k==0||head==NULL)returnhead;structNode*curr=head;intlen=1;// Find the length of linked listwhile(curr->next!=NULL){curr=curr->next;len+=1;}// Modulo k with length of linked list to handle// large values of kk%=len;if(k==0)returnhead;// Make the linked list circularcurr->next=head;// Traverse the linked list to find the kth nodecurr=head;for(inti=1;i<k;i++)curr=curr->next;// Update the (k + 1)th node as the new headhead=curr->next;// Break the loop by updating next pointer of kth nodecurr->next=NULL;returnhead;}voidprintList(structNode*node){while(node!=NULL){printf("%d ",node->data);node=node->next;}printf("\n");}intmain(){// Create a hard-coded linked list:// 10 -> 20 -> 30 -> 40structNode*head=createNode(10);head->next=createNode(20);head->next->next=createNode(30);head->next->next->next=createNode(40);head=rotate(head,6);printList(head);return0;}
Java
// Java program to rotate a linked list// by changing pointer of kth nodeclassNode{intdata;Nodenext;Node(intnew_data){data=new_data;next=null;}}// Function to rotate the linked list// to the left by k placesclassGfG{staticNoderotate(Nodehead,intk){// If the linked list is empty or no rotations are// needed, then return the original linked listif(k==0||head==null)returnhead;Nodecurr=head;intlen=1;// Find the length of linked listwhile(curr.next!=null){curr=curr.next;len+=1;}// Modulo k with length of linked list to handle// large values of kk%=len;if(k==0)returnhead;// Make the linked list circularcurr.next=head;// Traverse the linked list to find the kth nodecurr=head;for(inti=1;i<k;i++)curr=curr.next;// Update the (k + 1)th node as the new headhead=curr.next;// Break the loop by updating next pointer of kth nodecurr.next=null;returnhead;}staticvoidprintList(Nodenode){while(node!=null){System.out.print(node.data+" ");node=node.next;}System.out.println();}publicstaticvoidmain(String[]args){// Create a hard-coded linked list:// 10 -> 20 -> 30 -> 40Nodehead=newNode(10);head.next=newNode(20);head.next.next=newNode(30);head.next.next.next=newNode(40);head=rotate(head,6);printList(head);}}
Python
# Python program to rotate a linked list# by changing pointer of kth nodeclassNode:def__init__(self,newData):self.data=newDataself.next=None# Function to rotate the linked list to the left by k placesdefrotate(head,k):# If the linked list is empty or no rotations are needed, # return the original linked listifk==0orheadisNone:returnheadcurr=headlength=1# Find the length of the linked listwhilecurr.nextisnotNone:curr=curr.nextlength+=1# Modulo k with length of linked list to handle# large values of kk%=lengthifk==0:curr.next=Nonereturnhead# Make the linked list circularcurr.next=head# Traverse the linked list to find the kth nodecurr=headfor_inrange(1,k):curr=curr.next# Update the (k + 1)th node as the new headnewHead=curr.next# Break the loop by updating the next pointer# of kth nodecurr.next=NonereturnnewHeaddefprintList(node):whilenodeisnotNone:print(node.data,end=" ")node=node.nextprint()if__name__=="__main__":# Create a hard-coded linked list: 10 -> 20 -> 30 -> 40head=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 nodeusingSystem;publicclassNode{publicintdata;publicNodenext;publicNode(intnew_data){data=new_data;next=null;}}// Function to rotate the linked list// to the left by k placesclassGfG{staticNodeRotate(Nodehead,intk){// If the linked list is empty or no rotations are// needed, then return the original linked listif(k==0||head==null)returnhead;Nodecurr=head;intlen=1;// Find the length of linked listwhile(curr.next!=null){curr=curr.next;len+=1;}// Modulo k with length of linked list to handle// large values of kk%=len;if(k==0)returnhead;// Make the linked list circularcurr.next=head;// Traverse the linked list to find the kth nodecurr=head;for(inti=1;i<k;i++)curr=curr.next;// Update the (k + 1)th node as the new headNodenewHead=curr.next;// Break the loop by updating next pointer of kth nodecurr.next=null;returnnewHead;}staticvoidPrintList(Nodenode){while(node!=null){Console.Write(node.data+" ");node=node.next;}Console.WriteLine();}publicstaticvoidMain(){// Create a hard-coded linked list:// 10 -> 20 -> 30 -> 40Nodehead=newNode(10);head.next=newNode(20);head.next.next=newNode(30);head.next.next.next=newNode(40);head=Rotate(head,6);PrintList(head);}}
JavaScript
// JavaScript program to rotate a linked list// by changing pointer of kth nodeclassNode{constructor(new_data){this.data=new_data;this.next=null;}}// Function to rotate the linked list// to the left by k placesfunctionrotate(head,k){// If the linked list is empty or no rotations are// needed, then return the original linked listif(k===0||head===null)returnhead;letcurr=head;letlen=1;// Find the length of linked listwhile(curr.next!==null){curr=curr.next;len+=1;}// Modulo k with length of linked list to handle// large values of kk%=len;if(k===0){curr.next=null;returnhead;}// Make the linked list circularcurr.next=head;// Traverse the linked list to find the kth nodecurr=head;for(leti=1;i<k;i++)curr=curr.next;// Update the (k + 1)th node as the new headletnewHead=curr.next;// Break the loop by updating next pointer of kth nodecurr.next=null;returnnewHead;}functionprintList(node){letoutput='';while(node!==null){output+=node.data+' ';node=node.next;}console.log(output.trim());}// Create a hard-coded linked list:// 10 -> 20 -> 30 -> 40lethead=newNode(10);head.next=newNode(20);head.next.next=newNode(30);head.next.next.next=newNode(40);head=rotate(head,6);printList(head);
Output
30 40 10 20
Time Complexity: O(n), where n is the number of nodes in linked list. Auxiliary Space: O(1)
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.