0
点赞
收藏
分享

微信扫一扫

LeetCode Java刷题笔记—143. 重排链表

143. 重排链表

这题虽然是中等难度的题目,但实际上可以看做是链表简单题型的大乱炖,思路为:首先找到链表中点(LeetCode 876)断开成为两个链表,然后反转右边部分的链表节点(LeetCode 206),最后合并左右两个链表即可。

只要记住了思路,那么就比较容易写出来。

/**
 * 143. 重排链表
 * 给定一个单链表 L:L0→L1→…→Ln-1→Ln , 将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…。
 * 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
 * https://leetcode-cn.com/problems/reorder-list/
 * 中等
 */
public class LeetCode143 {

    /**
     * 首先找到链表中点(LeetCode 876,https://leetcode-cn.com/problems/middle-of-the-linked-list/)断开成为两个链表
     * 然后反转右边部分的链表节点(LeetCode 206,https://leetcode-cn.com/problems/reverse-linked-list/)
     * 最后合并左右两个链表即可。
     */
    public void reorderList(ListNode head) {
        if (head == null || head.next == null || head.next.next == null) {
            return;
        }
        /*找到链表中点*/
        ListNode slow = getMiddleNode(head);
        /*反转链表*/
        ListNode right = reverseList(slow.next);
        /*断开连接,这一步很重要*/
        slow.next = null;
        /*交叉合并链表*/
        mergeList(head, right);
    }

    private ListNode getMiddleNode(ListNode head) {
        ListNode slow = head, fast = head.next;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }


    private ListNode reverseList(ListNode head) {
        ListNode pre = null;
        while (head != null) {
            ListNode next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }

    private void mergeList(ListNode left, ListNode right) {
        while (left != null && right != null) {
            ListNode next = right.next;
            right.next = left.next;
            left.next = right;
            left = right.next;
            right = next;
        }
    }


    public class ListNode {

        int val;
        ListNode next;

        ListNode() {

        }

        ListNode(int val) {

            this.val = val;
        }

        ListNode(int val, ListNode next) {

            this.val = val;
            this.next = next;
        }
    }

}
举报

相关推荐

0 条评论