Rotate List in C++

Suppose we have a linked list. We have to rotate the list to the right k places. The value of k is not negative. So if the list is like [1,23,4,5,NULL], and k = 2, then the output will be [4,5,1,2,3,NULL]

Let us see the steps −

• If the list is empty, then return null
• len := 1
• create one node called tail := head
• while next of tail is not null
• increase len by 1
• tail := next of tail
• next of tail := head
• k := k mod len
• for i := 0 to len – k
• tail := next of tail
• newHead := next of tail
• next of tail := null

Let us see the following implementation to get better understanding −

Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
class ListNode{
public:
int val;
ListNode *next;
ListNode(int data){
val = data;
next = NULL;
}
};
ListNode *make_list(vector<int> v){
for(int i = 1; i<v.size(); i++){
while(ptr->next != NULL){
ptr = ptr->next;
}
ptr->next = new ListNode(v[i]);
}
}
cout << "[";
while(ptr->next){
cout << ptr->val << ", ";
ptr = ptr->next;
}
cout << "]" << endl;
}
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
int len = 1;
while(tail->next){
len++;
tail = tail->next;
}
k %= len;
for(int i = 0; i < len - k; i++){
tail = tail->next;
}
tail->next = NULL;
}
};
main(){
Solution ob;
vector<int> v = {1,2,3,4,5,6,7,8,9};