LeetCode(64)分隔链表【链表】【中等】

目录

链接: 分隔链表

1.题目

给你一个链表的头节点 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]

提示:

  • 链表中节点的数目在范围 [0, 200]
  • -100 <= Node.val <= 100
  • -200 <= x <= 200

2.答案

java 复制代码
/**
 * Definition for singly-linked list.
 * 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; }
 * }
 */
class Solution {
    public static ListNode partition(ListNode head, int x) {
        if (head == null) {
            return null;
        }
        ListNode node = head;
        ListNode beforeNode = null;
        ListNode firstBiggerNode = null;
        ListNode firstSmallerNode = null;
        ListNode smallerNode = null;
        while (node != null) {
            if (node.val < x) {
                if (firstSmallerNode == null) {
                    firstSmallerNode = node;
                }
                if (smallerNode != null) {
                    smallerNode.next = node;
                }
                if (beforeNode != null) {
                    beforeNode.next = node.next;
                }
                smallerNode = node;
            } else {
                if (firstBiggerNode == null) {
                    firstBiggerNode = node;
                }
                beforeNode = node;
            }
            node = node.next;
        }
        if (smallerNode != null) {
            smallerNode.next = firstBiggerNode;
            return firstSmallerNode;
        } else {
            return firstBiggerNode;
        }
    }
}

3.提交结果截图

整理完毕,完结撒花~ 🌻

相关推荐
地平线开发者3 小时前
SparseDrive 模型导出与性能优化实战
算法·自动驾驶
董董灿是个攻城狮4 小时前
大模型连载2:初步认识 tokenizer 的过程
算法
地平线开发者4 小时前
地平线 VP 接口工程实践(一):hbVPRoiResize 接口功能、使用约束与典型问题总结
算法·自动驾驶
罗西的思考4 小时前
AI Agent框架探秘:拆解 OpenHands(10)--- Runtime
人工智能·算法·机器学习
HXhlx8 小时前
CART决策树基本原理
算法·机器学习
Wect8 小时前
LeetCode 210. 课程表 II 题解:Kahn算法+DFS 双解法精讲
前端·算法·typescript
颜酱9 小时前
单调队列:滑动窗口极值问题的最优解(通用模板版)
javascript·后端·算法
Gorway15 小时前
解析残差网络 (ResNet)
算法
拖拉斯旋风16 小时前
LeetCode 经典算法题解析:优先队列与广度优先搜索的巧妙应用
算法
Wect16 小时前
LeetCode 207. 课程表:两种解法(BFS+DFS)详细解析
前端·算法·typescript