O(N) Java Solution

  • 1
    public ListNode oddEvenList(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode oddTail = head, evenTail, evenHead;
        evenHead = evenTail = head.next;
        while (evenTail != null && evenTail.next != null) {
            // move to the odd list tail.
            oddTail.next = evenTail.next;
            evenTail.next = evenTail.next.next;
            oddTail.next.next = evenHead;
            // move tails.
            oddTail = oddTail.next;
            evenTail = evenTail.next;
        return head;

  • 0

    I have a question with this line:

    ListNode oddTail = head, evenTail, evenHead;

    Is there some sort of implicit declaration going on?

    This is probably the right approach to solve this, btw. But I don´t recall this kind of sintax before.

        ListNode oddTail, evenTail, evenHead;
        oddTail = evenTail = evenHead = head;

    Is probably more readably, but that´s just me

  • 0

    Because your even list should start from the head.next.
    Java doesn't allow this:
    ListNode evenHead = evenTail = head.next; /* in this way, you can't declare and assign value at the same time. */
    So I choose to declare em first (with default value null in java).
    Hope it helps ;)

  • 0

    @Izana 's answer means:

    ListNode evenTail, evenHead, oddTail = head;

    Hope it helpful +_+

Log in to reply

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