Accepeted Recursive solution... Wondering if I can make it perform much better


  • 0
    S
    ListNode res, fast;
        int count, count2 = 0;
        boolean flag = true, rotateZero = false;
        public ListNode rotateRight(ListNode head, int k) {
    
            if (head == null || head.next == null || k == 0) return head;
    
            ListNode slow = head;
            fast = head;
            count = k;
    
            helper(slow);
    
            return res;
        }
    
        private void helper(ListNode slow) {
            if (slow == null) return;
    
            count2++; // gets the length of the linkedlist
    
            helper(slow.next);
    
            if(flag){
                count %= count2;
                System.out.println(count);
                flag = false;
                if(count == 0){ 
                    res = fast;
                    rotateZero = true;
                    return;
                }
            }
    
            if (rotateZero || count < 0) return; //list need not be rotated
    
            if (count == 0) {
                slow.next = null; //assign null to the last node
                count--;
                return;
            }
    
            slow.next = fast; //Assign last node to the current head
            fast = slow; //set the current head
    
            if (--count == 0) res = slow; //save the new head
        }
    

Log in to reply
 

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