Simple Java solution (beats 96.77% of submissions in 14 ms, O(n) time, O(1) space)


  • 1
    E
    public class Solution {
        public ListNode rotateRight(ListNode head, int k) {
            if(k < 0) return null;
            if(head == null || head.next == null || k == 0) return head;
            int length = 0, count = 1;
            ListNode currCount = head, curr = head, tail = null, prev = null;
            while(currCount.next != null){
                length++;
                currCount = currCount.next;
            }
            length++;
            tail = currCount;
            k %= length;
            if(k > 0){
                while((count <= length-k) && curr != null){
                    prev = curr;
                    curr = curr.next;
                    count++;
                }
                tail.next = head;
                prev.next = null;
                return curr;
            }
            return head;
        }
    }

Log in to reply
 

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