143. 重排链表

给定一个单链表 L 的头节点 head ,单链表 L 表示为:

L0 → L1 → … → Ln - 1 → Ln
请将其重新排列后变为:

L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …
不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reorder-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

class Solution {

    private static ListNode reverse(ListNode head) {
        ListNode pre = null, cur = head, next;

        while (cur != null) {
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }

        return pre;
    }

    /**
     * 上中节点
     *
     * @param head
     * @return
     */
    private static ListNode findMid(ListNode head) {
        if (head == null || head.next == null || head.next.next == null) {
            return head;
        }
        ListNode slow = head.next;
        ListNode fast = head.next.next;
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }

    private static ListNode merge(ListNode head1, ListNode head2) {

        ListNode newHead = new ListNode(), tail = newHead;

        while (head1 != null && head2 != null) {

            ListNode next1 = head1.next;
            ListNode next2 = head2.next;

            tail.next = head1;
            tail = tail.next;

            tail.next = head2;
            tail = head2;

            head1 = next1;
            head2 = next2;
        }

        if (head1 != null) {
            tail.next = head1;
        }

        if (head2 != null) {
            tail.next = head2;
        }

        return newHead.next;
    }

    private static ListNode[] split(ListNode head) {
        ListNode newHead1 = new ListNode(), tail1 = newHead1;
        ListNode newHead2 = new ListNode(), tail2 = newHead2;

        while (head != null) {
            tail1.next = head;
            tail1 = head;
            head = head.next;
            tail1.next = null;
            if (head != null) {
                tail2.next = head;
                tail2 = head;
                head = head.next;
                tail2.next = null;
            }
        }

        return new ListNode[]{newHead1.next, newHead2.next};
    }

    public static void reorderList(ListNode head) {
        if (head == null || head.next == null || head.next.next == null) {
            return;
        }
        ListNode mid = findMid(head);
        ListNode midNext = mid.next;
        mid.next = null;
        ListNode head1 = head;
        ListNode head2 = reverse(midNext);
        merge(head1, head2);
    }
}


class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}

posted @ 2021-12-07 18:01  Tianyiya  阅读(25)  评论(0)    收藏  举报