I have the same problem.


  • 0
    L

    I pasted my code here, I didn't use the approach that reverse the second half of the list, but I think my solution should also work. Could anyone point out where I'm wrong please. I failed to pass the input of :Last executed input: {3,2,3,3,3,1,3,1,3,3,1,1,3,3,2,1,1,1,1,2,1,1,2,1,2,1,3,2,...........

    public class Solution  {
    public void reorderList(ListNode head) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        ListNode slow = head;
        ListNode fast = head;
        boolean odd = false;
        if (head==null){
            return;
        }
        while (fast.next!=null && fast.next.next!=null){
            fast = fast.next.next;
            slow = slow.next;
        }
        if (fast.next==null){
            odd = true;
        }
        reorder (odd, slow, head);
    }
    
    public ListNode reorder(boolean odd, ListNode mid, ListNode head){
        ListNode res;
        if (head==mid){
            if (odd){
                res = head.next;
                head.next=null;
                return res;
            }
            res = head.next.next;
            head.next.next=null;
            return res;
        }
        
        ListNode current = reorder(odd, mid, head.next);
        res = current.next;
        current.next = head.next;
        head.next = current;
        return res;
    }
    

    }


  • 2
    M

    I met the same problem before. I guess it is because the recursion depth is too large, then cause stack over flow. Then I implement it using iterative method, it accepted.


  • 0
    L

    cool, thank you!


  • 0
    O

    Thanks! That should be the problem


Log in to reply
 

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