1ms java solution with one loop

  • 0
    public ListNode rotateRight(ListNode head, int k) {
        if(head== null || head.next== null || k== 0){    return head;}
        int cnt=0;
        ListNode fast = head, slow=null;
        while(fast.next!= null){
            if(cnt== k+1){  slow= head;}
            fast = fast.next;
            if(cnt> k){ slow= slow.next;}
            if(fast.next == null){
                if(cnt== k+1){  slow= head; break; }
                if(k% cnt == 0){    return head;}
                if(k> cnt){    k%= cnt; fast= head; cnt=0; }
        ListNode head2 = slow.next;
        slow.next = null;
        fast.next = head;
        return head2;

Log in to reply

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