My simple java solution


  • 0
    J
        public ListNode rotateRight(ListNode head, int k) {
            ListNode dummy = new ListNode(0), node = head;
            dummy.next = head;
            if(head == null || head.next == null) return head;
            
            // Count the length of the list
            int len = 1;
            while(node.next != null){
                node = node.next; 
                len++;
            }
            
            //Rotate the list
            if(k % len != 0){
                int rotateNum = k % len;
                int n = len - rotateNum;
                ListNode p = head, pre = head;
                for(int i = 0; i < n; i++){
                    pre = p;
                    p = p.next;
                }
                dummy.next = p;
                node.next = head;
                pre.next = null;
            }
            return dummy.next;
        }

Log in to reply
 

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