Simple Java solution, cost O(N)(n>k) or O(2N)(n<k) in time, O(1) in space


  • 0
    Y
    public ListNode rotateRight(ListNode head, int k) {
        if(head==null||head.next==null||k==0) return head;
        ListNode begin = head;
        ListNode end = head.next;
        for(int count=1;count<k;count++){
            end=end.next;
            if(end==null){
                end=head;
                count=(k/(count+1))*(count+1)-1; //k>=n, this sentence could avoid useless repeat
            }
        }
        while(end.next!=null){
            begin=begin.next;
            end=end.next;
        }
        end.next=head;
        head=begin.next;
        begin.next=null;
        return head;
    }

Log in to reply
 

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