Easy and straightforward JAVA solution


  • 2

    An easy solution:

    public ListNode rotateRight(ListNode head, int k) {
        if(head == null || head.next == null) return head;
        
        // Get length
        int len = 1;
        ListNode tail = head;
        while(tail.next != null) {
            tail = tail.next;
            len++;
        }
        
        // Go to position k distance to tail
        k = k % len;
        if(k == 0) return head;
        ListNode newTail = head;
        for(int i = 0; i < len - k - 1; i++) {
            newTail = newTail.next;
        }
        
        // Join two parts
        ListNode newHead = newTail.next;
        newTail.next = null;
        tail.next = head;
        
        return newHead;
    }

Log in to reply
 

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