Java recursive O(n) solution


  • 0
    B
    class Solution {
        private static ListNode headItr = null;
        private static boolean stopExchange = false;
        public void reorderList(ListNode head) {
            headItr = head;
            head = reOrderUtil(head);
        }
        
        private ListNode reOrderUtil(ListNode curr) {
            if (curr == null) {
                return null;
            }
    
            ListNode last = reOrderUtil(curr.next);
            if(headItr == last || headItr.next == last) {
                stopExchange = true;
            }
            if (last != null && !stopExchange) {
                ListNode temp = headItr.next;
                if(headItr.next != null) {
                    headItr.next = last;
                }
                last.next = temp;
                headItr = temp;
                curr.next = null;
            }
            return curr;
        }
    }
    

Log in to reply
 

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