Simple O(n) Java Solution w/ comments

  • 1

    public class Solution {
    public ListNode rotateRight(ListNode head, int k) {
    int size = 1;

        if(head == null)
            return null;
        ListNode current = head;
        //Count size of the list and puts current pointer at the end
        while( != null)
            current =;
        //To deal with the case k >= size
        k %= size;
        //Puts the head of the list next to the tail. The idea is to use this to find the new head = head;
        //We need to iterate size - k times to find the new head.
        for(int i = 0; i < size - k; i++)
            current =;
        //Sets the new head
        head =;
        //Current is the tail of our new list. Thus, this sets the null as the next node = null;
        return head;


Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.