A Slightly Different Java Solution (without even/odd pointers)

  • 2

    I iterate through the list until I hit the second-to-last node. Until then, each node's next pointer is set to the node two ahead of it. At the end, I see if I'm looking at an even node or an odd node, using the index variable. If it's an odd node, I just point it to the first even (head.next, reserved). Otherwise, I point it to null and point the next one to the first even.

    Not as compact as the other solutions, but that's how I thought of it.

    public ListNode oddEvenList(ListNode head) {
        if(head == null) return null;
        int index = 1;
        ListNode node = head;
        ListNode node2 = head.next;
        while(node.next != null && node.next.next != null) {
            ListNode temp = node.next;
            node.next = temp.next;
            node = temp;
        if(index % 2 == 1) {
            node.next = node2;
        else {
            ListNode temp = node.next;
            node.next = null;
            temp.next = node2;
        return head;

Log in to reply

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