My 99.3 % java solution


  • 0
    9

    public class Solution {
    public ListNode rotateRight(ListNode head, int k) {
    if(head == null || head.next==null || k==0)
    {
    return head;
    }
    ListNode fast = head;
    ListNode slow = head;

        int count = 0 ;
        for(int i=0; i<k; i++)
        {
            if(fast!=null){
                fast = fast.next;
                count +=1;
            }else{
                break;
            }
        }
    
        if(fast == null){
            k = k % count;
            fast = head;
            if(k == 0)
                return head;
            for (int i=0; i< k;i++)
            {
                fast = fast.next;
            }
        }
        
        while(fast.next != null)
        {
            fast = fast.next;
            slow = slow.next;
        }
        
        ListNode newHead = slow.next;
        slow.next = null;
        fast.next = head;
        return newHead;
    }
    

    }


Log in to reply
 

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