leetcode佛系刷题-86.分隔链表

题目:

给你一个链表的头节点 head 和一个特定值 x ,请你对链表进行分隔,使得所有 小于 x 的节点都出现在 大于或等于 x 的节点之前。你应当 保留 两个分区中每个节点的初始相对位置。

示例 1:

输入:head = [1,4,3,2,5,2], x = 3
输出:[1,2,2,4,3,5]

示例 2:

输入:head = [2,1], x = 2
输出:[1,2

思路分析:

这道题目比较简单,它是一道分隔链表的题目,需要将小于 x 的节点和大于等于 x 的节点分隔开来,并且保留它们在原始链表中的相对顺序。我们可以通过创建两个新的链表,分别存放小于 x 的节点和大于等于 x 的节点,这里使用尾插法,因为要保证相对顺序,最后将这两个链表合并起来即可。

具体代码及详细注释如下:

class Solution {
    public ListNode partition(ListNode head, int x) {
        // 创建两个虚拟头节点,分别用于存放小于 x 的节点和大于等于 x 的节点
        ListNode smallerXNode = new ListNode(0); // 小于 x 的节点链表头节点
        ListNode NoSmallerXNode = new ListNode(0); // 大于等于 x 的节点链表头节点

        // 创建两个指针,用于遍历两个分区的链表
        ListNode smallerp = smallerXNode; // 小于 x 的节点链表指针
        ListNode nosmallerq = NoSmallerXNode; // 大于等于 x 的节点链表指针

        // 遍历原始链表
        while (head != null) {
            if (head.val < x) {
                // 如果当前节点值小于 x,则将其连接到小于 x 的节点链表
                smallerp.next = head;
                smallerp = smallerp.next;
            } else {
                // 如果当前节点值大于等于 x,则将其连接到大于等于 x 的节点链表
                nosmallerq.next = head;
                nosmallerq = nosmallerq.next;
            }
            head = head.next; // 移动到下一个节点
        }

        // 将两个分区合并
        smallerp.next = NoSmallerXNode.next;
        nosmallerq.next = null;

        // 返回分隔后的链表头节点
        return smallerXNode.next;
    }
}

好久没写代码了,开始恢复吧,会陆续刷题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

开心码

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

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

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

打赏作者

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

抵扣说明:

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

余额充值