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.提交结果截图

整理完毕,完结撒花~ 🌻

相关推荐
停停的茶1 小时前
决策树(2)
算法·决策树·机器学习
汤永红1 小时前
week2-[一维数组]最大元素
数据结构·c++·算法·信睡奥赛
菜鸟555554 小时前
图论:Floyd算法
算法·图论
呼啦啦啦啦啦啦啦啦9 小时前
常见的排序算法
java·算法·排序算法
胡萝卜3.010 小时前
数据结构初阶:排序算法(一)插入排序、选择排序
数据结构·笔记·学习·算法·排序算法·学习方法
地平线开发者10 小时前
LLM 中 token 简介与 bert 实操解读
算法·自动驾驶
scx2013100410 小时前
20250814 最小生成树和重构树总结
c++·算法·最小生成树·重构树
阿巴~阿巴~11 小时前
冒泡排序算法
c语言·开发语言·算法·排序算法
散11211 小时前
01数据结构-交换排序
数据结构·算法
yzx99101311 小时前
Yolov模型的演变
人工智能·算法·yolo