LeetCode 面试题 02.04. 分割链表

文章目录

一、题目

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

二、C# 题解

最初打算在原链表上改,想了很久发现难以操作,需要引入队列。最后决定,不如直接新建两个链表 smalllarge,分别用于添加节点值 < x < x <x 和节点值 ≥ x \geq x ≥x 的节点。

遍历链表 head 后,拼接 smalllarge 链表,最终返回头节点 small.next 即可。

csharp 复制代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode Partition(ListNode head, int x) {
        ListNode small = new ListNode(0), large = new ListNode(0);
        ListNode p = small, q = large; // p 指向 small 尾端,q 指向 large 尾端

        while (head != null) {  // 遍历原链表
            if (head.val < x) { // 小值放入 small 链表中
                p.next = head;
                p = p.next;
            }
            else {
                q.next = head;  // 大值放入 large 链表中
                q = q.next;
            }

            head = head.next;
        }

        p.next = large.next;    // 连接两个链表
        q.next = null;          // 断后

        return small.next;
    }
}
  • 时间复杂度: O ( n ) O(n) O(n)。
  • 空间复杂度: O ( n ) O(n) O(n)。
相关推荐
黎阳之光23 分钟前
黎阳之光:视频孪生领跑者,铸就中国数字科技全球竞争力
大数据·人工智能·算法·安全·数字孪生
skywalker_1130 分钟前
力扣hot100-3(最长连续序列),4(移动零)
数据结构·算法·leetcode
6Hzlia31 分钟前
【Hot 100 刷题计划】 LeetCode 17. 电话号码的字母组合 | C++ 回溯算法经典模板
c++·算法·leetcode
我是唐青枫1 小时前
C#.NET gRPC 深入解析:Proto 定义、流式调用与服务间通信取舍
开发语言·c#·.net
wfbcg1 小时前
每日算法练习:LeetCode 209. 长度最小的子数组 ✅
算法·leetcode·职场和发展
_日拱一卒1 小时前
LeetCode:除了自身以外数组的乘积
数据结构·算法·leetcode
计算机安禾1 小时前
【数据结构与算法】第36篇:排序大总结:稳定性、时间复杂度与适用场景
c语言·数据结构·c++·算法·链表·线性回归·visual studio
unicrom_深圳市由你创科技1 小时前
做虚拟示波器这种实时波形显示的上位机,用什么语言?
c++·python·c#
SatVision炼金士1 小时前
合成孔径雷达干涉测量(InSAR)沉降监测算法体系
算法
wuweijianlove1 小时前
算法稳定性与数值误差传播研究的技术2
算法