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 小时前
ch03 部分题目思路
算法
山登绝顶我为峰 3(^v^)32 小时前
如何录制带备注的演示文稿(LaTex Beamer + Pympress)
c++·线性代数·算法·计算机·密码学·音视频·latex
Two_brushes.3 小时前
【算法】宽度优先遍历BFS
算法·leetcode·哈希算法·宽度优先
森焱森6 小时前
水下航行器外形分类详解
c语言·单片机·算法·架构·无人机
QuantumStack7 小时前
【C++ 真题】P1104 生日
开发语言·c++·算法
写个博客8 小时前
暑假算法日记第一天
算法
绿皮的猪猪侠8 小时前
算法笔记上机训练实战指南刷题
笔记·算法·pta·上机·浙大
hie988949 小时前
MATLAB锂离子电池伪二维(P2D)模型实现
人工智能·算法·matlab
杰克尼9 小时前
BM5 合并k个已排序的链表
数据结构·算法·链表
.30-06Springfield10 小时前
决策树(Decision tree)算法详解(ID3、C4.5、CART)
人工智能·python·算法·决策树·机器学习