My simple Java solution


  • 0

    1 pre-process k by k%len while get tail at the same time

    2 Concatenate head to tail

    3 Find the newtail by head+len-k-1

    4 Set newtail.next as null

    public class Solution {
      public ListNode rotateRight(ListNode head, int k) {
        if(head==null || k==0) return head;
        int len=1,i=0;
        ListNode tail, nhead, ntail;
        //get length
        for(tail=head;tail.next!=null;tail = tail.next,len++);
        k = k%len;
        if(k==0) return head;
        //concatenate tail to head
        tail.next = head;
        //get new tail
        for(ntail=head,i=0;i<len-k-1;ntail = ntail.next, i++);
        //get new head
        nhead = ntail.next;
        //set new tail
        ntail.next = null;
        return nhead;
      }
    }
    

    `


Log in to reply
 

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