[LeetCode] 143. 重排链表

这个题感觉很不错,链表中的部分反转问题、快慢指针问题都可以考察到。

首先,利用快慢指针,找到链表的中位节点,然后对后半部分链表反转。然后对前半部分链表隔一个插入一个就可以了。

143. 重排链表

``` class Solution { public void reorderList(ListNode head) { ListNode fast = head; ListNode slow = head;
    while (fast != null) {
        fast = fast.next;
        if (fast == null) break;
        slow = slow.next;
        fast = fast.next;
    }

    fast = reverse(slow.next);
    
    slow.next = null;
    slow = head;
    while (fast != null) {
        ListNode next = slow.next;

        slow.next = fast;
        fast = fast.next;

        slow.next.next = next;
        slow = slow.next.next;
    }
}

private ListNode reverse(ListNode head) {
    if (head == null) return null;

    ListNode cur = head;
    ListNode last = null;
    ListNode next = null;
    while (cur != null) {
        next = cur.next;
        cur.next = last;

        last = cur;
        cur = next;
    }

    return last;
}

}

posted @ 2021-06-06 23:47  ACBingo  阅读(36)  评论(0编辑  收藏  举报