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 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;!=null;tail =,len++);
        k = k%len;
        if(k==0) return head;
        //concatenate tail to head = head;
        //get new tail
        for(ntail=head,i=0;i<len-k-1;ntail =, i++);
        //get new head
        nhead =;
        //set new tail = null;
        return nhead;


Log in to reply

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