Java recursion stack over flow?


  • 0
    D

    Hi guys this is my code, is there a way to optimize my code so the stack doesn't over flow?

    public class Solution {
        
        private ListNode dummy = new ListNode( -1 );
        private ListNode ptr = dummy;
        private ListNode hptr;
        private boolean bb = false;
        
        private void recur( ListNode head ) {
            if ( head == null ) {
                return;
            }
            
            recur( head.next );
            if ( this.bb != true ) {
                ptr.next = hptr;
                ptr = ptr.next;
                hptr = hptr.next;
                if ( ptr == head ) {
                    ptr.next = null;
                    this.bb = true;
                    return;
                }
                ptr.next = head;
                ptr = ptr.next;
                if ( hptr == head ) {
                    ptr.next = null;
                    this.bb = true;
                    return;
                }
            }
        }
        
        public void reorderList(ListNode head) {
            
            if ( head == null || head.next == null ) {
                return;
            }
            
            this.hptr = head;
            this.recur( head );
        }
    }
    

Log in to reply
 

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