Clean and simple JAVA solution


  • 0
    C
    /**
     * 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)
        {
            int n = 0;
            
            if(null == head)
            {
                return head;
            }
            
            ListNode iter = head, prev = null;
            
            while(null != iter)
            {
                prev = iter;
                iter = iter.next;
                n++;
            }
            
            prev.next = head;
            
            iter = head;
            
            k = k % n;
            
            for(int i = 0; i < n - k && null != iter; i++)
            {
                prev = iter;
                iter = iter.next;
            }
            
            ListNode newHead = iter;
            prev.next = null;
            
            return newHead;
            
        }
    }

Log in to reply
 

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