Simple Java Solution with Explanation


  • 17
    B

    We just need to form a linked list of all odd nodes(X) and another linked list of all even nodes(Y). Afterwards, we link Y to the end of X, and return the head of X.

    public ListNode oddEvenList(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        ListNode odd = head;
        ListNode even = head.next;
        ListNode even_head = head.next;
        while(even != null && even.next != null){
            odd.next = odd.next.next;
            even.next = even.next.next;
            odd = odd.next;
            even = even.next;
        }
        odd.next = even_head;
        return head;
    }

  • -21
    R

    The question asks you to solve the problem in O(1) space. Since you are creating two additional linked lists and then linking those together, how is this in O(1) space?


  • 0
    H

    Above solution is not using any extra space to save the list nodes. It is just updating the next pointers for each node which ultimately points to same nodes in the original list. So it is still O(1) in space.


  • 0
    Y

    same method, my runtime is 1min. Why so slow?


  • 0

    this is not "in place"?


Log in to reply
 

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