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

143. 重排链表

给定一个单链表 L:L0→L1→…→Ln-1→Ln , 将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…。你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

这题虽然是中等难度的题目,但实际上可以看做是链表简单题型的大乱炖,思路为:首先找到链表中点(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;
        }
    }

}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

刘Java

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值