ListNode* Solution::rotateRight(ListNode* A, int B) {

// If the list is empty or B is 0 return A.

if(A == NULL || B == 0){

return A;

}

ListNode *temp = A;

int count = 0;

// count no.of nodes in the given list

while(temp != NULL){

count++;

temp = temp->next;

}

// if given B is greater than no. of nodes in the list then, we find an effective number to shift the list by right.

int r = B%count;

// if r is 0 the list will end up with the same original head even after rotation.

if(r == 0 && B>=count){

return A;

}

int i = 0;

temp = A;

// Initialize a node to keep track of previous node.

ListNode *prev = NULL;

// Run a while loop to find the new_head node.

while(i<count - r){

prev = temp;

temp = temp->next;

i++;

}

ListNode *new_head = temp;

// After finding the new_head the prev node should be pointing to NULL since it is the tail node of the rotated list.

prev->next = NULL;

// run a while loop and to find the tail node of the original list.

while(temp->next!=NULL){

temp = temp->next;

}

// Now the original tail node should be pointing to the original head node.

temp->next = A;

return new_head;

}