Java Simple Recursive Solution: (but stackoverflow ...)


  • 0
    K

    public class Solution {

    private ListNode first;
    
    public void reorderList(ListNode head) {
        if (head == null) {
            return;
        }
        first = head;
        recurse(head);
    }
    
    private ListNode recurse(ListNode node) {
        if (node == null || node.next == null) {
            return node;
        }
        
        ListNode last = recurse(node.next);
        
        if (first != null && last != null && first != last && first.next != last) {
            ListNode second = first.next;
            first.next = last;
            last.next = second;
            first = second;
            node.next = null;
            return node;
        } else {
            return null;
        }
    }
    

    }


Log in to reply
 

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