Java solution: only 2n - k iterations


  • 0
    D
    public class Solution {
        public ListNode rotateRight(ListNode head, int k) {
            if (head == null || head.next == null) return head;
            
            ListNode newHead, ptr = head;
            int length = 1; // because we start at head
            
            while (ptr.next != null) { // get length of list
                ptr = ptr.next;
                length++;
            } // ptr is pointing at the tail node
            k = k % length;
            ptr.next = head; // make the list a cycle
            
            for (int i = 0; i < length - k; i++)
                ptr = ptr.next;
            
            // set the new head to the item after it
            newHead = ptr.next;
            ptr.next = null; // break cycle, and make list have a tail
            return newHead;
        }
    }
    

Log in to reply
 

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