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

整理完毕,完结撒花~ 🌻

相关推荐
FL16238631299 分钟前
基于C#winform部署软前景分割DAViD算法的onnx模型实现前景分割
开发语言·算法·c#
baizhigangqw1 小时前
启发式算法WebApp实验室:从搜索策略到群体智能的能力进阶
算法·启发式算法·web app
C雨后彩虹1 小时前
最多等和不相交连续子序列
java·数据结构·算法·华为·面试
cpp_25012 小时前
P2347 [NOIP 1996 提高组] 砝码称重
数据结构·c++·算法·题解·洛谷·noip·背包dp
Hugh-Yu-1301232 小时前
二元一次方程组求解器c++代码
开发语言·c++·算法
编程大师哥2 小时前
C++类和对象
开发语言·c++·算法
加农炮手Jinx3 小时前
LeetCode 146. LRU Cache 题解
算法·leetcode·力扣
Rabitebla3 小时前
C++ 和 C 语言实现 Stack 对比
c语言·数据结构·c++·算法·排序算法
加农炮手Jinx3 小时前
LeetCode 128. Longest Consecutive Sequence 题解
算法·leetcode·力扣
旖-旎3 小时前
递归(汉诺塔问题)(1)
c++·学习·算法·leetcode·深度优先·递归