Easy solution c++ with comments


#1

ListNode* Solution::rotateRight(ListNode* A, int B) {
int i=1;
ListNode* len=A;
ListNode* prev=NULL;
ListNode* nth=A;
ListNode* l=A;
ListNode* head=A;
if(A->next==NULL) return A;
while(l->next!=NULL){
i++;prev=l; //get the length of list …and keep track of last 2 elemts
l=l->next;
}
//cout<val<<" "<val<<endl;
if(i<B){
B=B%i;
}
if(B==0) return A;
while(B–){
len=len->next; // traverse till B
}
while(len->next!=NULL){
nth=nth->next; // store the len node(which travelld B times) in nth node and travel till null…
len=len->next; // which gives us Bth element from last.
} //store in new list (s) //coz this wd be our start of our new rotated list
ListNode* r=nth->next;
ListNode* s=nth->next;
nth->next=NULL;
while(r->next!=NULL){
r=r->next; //traverse till the end then point it to the frst node
}
r->next=A;
return s;
}