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

整理完毕,完结撒花~ 🌻

相关推荐
搂鱼1145141 小时前
GJOI 10.20/10.22 题解
算法
我搞slam1 小时前
插入区间--leetcode
算法·leetcode
前进之路91 小时前
Leetcode每日一练--40
算法·leetcode
Swift社区1 小时前
LeetCode 405 - 数字转换为十六进制数
算法·leetcode·职场和发展
赵杰伦cpp1 小时前
数据结构——二叉搜索树深度解析
开发语言·数据结构·c++·算法
大数据张老师1 小时前
数据结构——希尔排序
数据结构·算法·排序算法·1024程序员节
第七序章2 小时前
【C + +】unordered_set 和 unordered_map 的用法、区别、性能全解析
数据结构·c++·人工智能·算法·哈希算法·1024程序员节
草莓熊Lotso2 小时前
《算法闯关指南:优选算法--二分查找》--23.寻找旋转排序数组中的最小值,24.点名
开发语言·c++·算法·1024程序员节
文火冰糖的硅基工坊2 小时前
[嵌入式系统-150]:智能机器人(具身智能)内部的嵌入式系统以及各自的功能、硬件架构、操作系统、软件架构
android·linux·算法·ubuntu·机器人·硬件架构
郝学胜-神的一滴3 小时前
主成分分析(PCA)在计算机图形学中的深入解析与应用
开发语言·人工智能·算法·机器学习·1024程序员节