My short java solution with comments


  • 14
    B
    public ListNode rotateRight(ListNode head, int k) {
        if(head==null||head.next==null||k==0) return head;
        
        //make it a cricle, break from k postion far from the head
        ListNode index=head; int len=1;// int len to record the length of list
        while(index.next!=null)
        {index=index.next; len++;}
        index.next=head;
        
        for(int i=0;i<len-k%len;i++)
        {
           index=index.next;
        }
        ListNode result=index.next;
        index.next=null;
        return result;
    }

  • 0
    J

    That is a very smart solution.


  • 0
    H

    for(int i=0;i<len-k%len;i++) this made you code shorter. but you will need to calculate k-k%len several times.


  • 0
    B

    Right.you got it.


  • 0
    J

    That's a great idea!


Log in to reply
 

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