LeetCode143. 重排链表

思路:

  1. 快慢指针找到中间节点,切成两半。(注意链表长度的奇偶性)
  2. 后半部分 reverse 操作。
  3. 归并操作,即后半部分 塞到 前半部分的“缝隙”里,组成新的链表。
class Solution {
    public void reorderList(ListNode head) {
        if (head == null || head.next == null) return;
        // Step1. 找到中间节点
        ListNode fast = head, slow = head;
        while (fast.next != null && fast.next.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }

        // Step2:切成两半,后半部分reverse
        ListNode l2 = slow.next;
        slow.next = null;
        l2 = reverse(l2);
        ListNode l1 = head;

        // Step3:后半部分塞到 前半部分的"缝隙"里
        while (l1 != null && l2 != null) {
            ListNode next1 = l1.next;
            l1.next = l2;
            ListNode next2 = l2.next;
            l2.next = next1;

            l1 = next1;
            l2 = next2;
        }
    }
    // 反转链表
    private ListNode reverse(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode cur = head;
        ListNode pre = null, next = null;
        while (cur != null) {
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
}

 

posted @ 2020-12-14 22:26  不学无墅_NKer  阅读(33)  评论(0编辑  收藏  举报