LeetCode_143. 重排链表(获取链表中点/翻转链表/合并两个链表)

LeetCode_143. 重排链表(获取链表中点/翻转链表/合并两个链表)

思路

  1. 首先找到链表的中点(LeetCode #876)
	// 找到中间节点
    public ListNode getMid(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;

        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }
  1. 将链表中点后面的元素反转(LeetCode #206)
	// 对中间节点后面的部分进行反转
    public ListNode reserve(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        while (cur != null) {
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
  1. 中点前和中点后两个部分进行合并
	// 合并两个链表
    public void mager(ListNode head1, ListNode head2) {
        while (head1 != null && head2 != null) {
            ListNode next1 = head1.next;
            ListNode next2 = head2.next;

            head1.next = head2;
            head2.next = next1;

            head1 = next1;
            head2 = next2;
        }
    }

代码实现(java)

class Solution {
    public void reorderList(ListNode head) {
        if (head == null || head.next == null) return;
        // 首先获取链表的中点
        ListNode mid = getMid(head);

        // 然后对中点后面的部分进行反转
        ListNode head2 = mid.next;
        mid.next = null;
        head2 = reserve(head2);

        // 合并链表
        ListNode head1 = head;
        mager(head1, head2);
    }

    // 找到中间节点
    public ListNode getMid(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;

        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }

    // 对中间节点后面的部分进行反转
    public ListNode reserve(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        while (cur != null) {
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }

    // 合并两个链表
    public void mager(ListNode head1, ListNode head2) {
        while (head1 != null && head2 != null) {
            ListNode next1 = head1.next;
            ListNode next2 = head2.next;

            head1.next = head2;
            head2.next = next1;

            head1 = next1;
            head2 = next2;
        }
    }
}
上一篇:【143期】你知道 Java 是如何实现线程间通信的吗?


下一篇:【Leetcode】143. 重排链表