Java iterative solution with comments


#1
public class Solution {
    public ListNode rotateRight(ListNode A, int B) {
        int size = size(A);
        int rotations = B%size;
        if(A == null) {
            return null;
        } else if(size == 1 || rotations == 0) { // If no rotations required
            return A;
        }
        
        ListNode temp = A;
        ListNode tempNext = null;
        ListNode newHead = null;
        int count = 1;
        while(count < size - rotations) { // To get the new tail of the list 
            temp = temp.next;
            count++;
        }
        
        tempNext = temp.next; // To get the newhead of list
        temp.next = null; // Do tail.next to null for the new tail
        newHead = tempNext; // This is the new head of the list
        while(tempNext.next != null) {// Traverse till previous list tail
            tempNext = tempNext.next;
        }
        tempNext.next = A;// Do tail.next to previous head
        return newHead;
    }
    
    public int size(ListNode A) {
        int count = 0;
        while(A != null) {
            A = A.next;
            count++;
        }
        return count;
    }
}