Java 15ms solutions, very simple! (no length required in best cases)


  • 0
    M

    This solution combines the following two cases:

    1. K < length (no addition pass required in order to count the length)
    2. K > length ( the same as other solutions)

    The advantage of solution is no addition pass required when K < length (considering the length of the List could be very large).

    public class Solution {
        public ListNode rotateRight(ListNode head, int k) {
            if(head == null)
                return head;
            ListNode headPointer = head;
            ListNode endPointer = head;
            int len = 0;
            while(k-- > 0) {
                if(endPointer.next == null) {
                    endPointer = head;
                    k = k % (len + 1);
                } else {
                    endPointer = endPointer.next;
                    len++;
                }
            }
    
            while(endPointer.next != null) {
                headPointer = headPointer.next;
                endPointer = endPointer.next;
            }
            endPointer.next = head;
            ListNode newHead = headPointer.next;
            headPointer.next = null;
            return newHead;
        }
    }
    

Log in to reply
 

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