My Java Solution


  • 0
    E
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode rotateRight(ListNode head, int k) {
            if(k==0 || head==null || head.next==null){
                return head;
            }
            int len=0;
            ListNode start=head;
            while(start!=null){
                len++;
                start=start.next;
            }
            k=k%len;
            k=len-k;
            start=head;
            ListNode move=null,curr=null;
            while(k!=0 && start!=null){
                if(move==null){
                    move=new ListNode(start.val);
                    curr=move;
                }
                else{
                    curr.next=new ListNode(start.val);
                    curr=curr.next;
                }
                start=start.next;
                k--;
            }
            if(start==null){
                return move;
            }
            curr=start;
            while(curr!=null && curr.next!=null){
                curr=curr.next;
            }
            if(curr!=null){
               curr.next=move; 
            }
            
            return start;
        }
    }
    

Log in to reply
 

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