[leetcode] - 328. Odd Even Linked List

题意是要将所有序号为奇数的节点全部放在链表前面,序号为偶数的连在最后一个奇数节点后面,并且不能打乱顺序。主要序号定义为从节点头顺序编号,不是指节点的值。

这道题略坑,本想着可以直接ac的,代码也比较优雅, 结果发现leetcode这道题对空间的要求极高,如果你不马上把用完的空间释放掉,分分钟叫你重写。

未ac版本:

public ListNode oddEvenList(ListNode head) {

        ListNode tmpEven = new ListNode(0);
        ListNode tmpOdd = new ListNode(0);
        ListNode even = tmpEven;
        ListNode odd = tmpOdd;
        boolean isOdd = true;

        while (head != null) {
            if (isOdd) {
                tmpOdd.next = head;
                tmpOdd = tmpOdd.next;
            } else {
                tmpEven.next = head;
                tmpEven = tmpEven.next;
            }
            head = head.next;
            isOdd = !isOdd;
        }
        tmpOdd.next = even.next;
        return odd.next;
    }

修改后的版本

  public ListNode oddEvenList(ListNode head) {

        if (head == null || head.next == null || head.next.next == null) return head;
        ListNode tmpOdd = head;
        ListNode tmpEven = head.next;
        ListNode Even = tmpEven;
        ListNode current = tmpEven.next;
        boolean isOdd = true;
        while (current != null) {
            if (isOdd) {
                tmpOdd.next = current;
                tmpOdd = current;
            } else {
                tmpEven.next = current;
                tmpEven = current;
            }
            current = current.next;
            isOdd = !isOdd;
        }
        tmpEven.next = null;
        tmpOdd.next = Even;
        return head;
    }
点赞