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)。
相关推荐
孤飞3 分钟前
zero2Agent:面向大厂面试的 Agent 工程教程,从概念到生产的完整学习路线
算法
技术专家1 小时前
Stable Diffusion系列的详细讨论 / Detailed Discussion of the Stable Diffusion Series
人工智能·python·算法·推荐算法·1024程序员节
csdn_aspnet2 小时前
C# (QuickSort using Random Pivoting)使用随机枢轴的快速排序
数据结构·算法·c#·排序算法
鹿角片ljp2 小时前
最长回文子串(LeetCode 5)详解
算法·leetcode·职场和发展
paeamecium3 小时前
【PAT甲级真题】- Cars on Campus (30)
数据结构·c++·算法·pat考试·pat
chh5634 小时前
C++--模版初阶
c语言·开发语言·c++·学习·算法
RTC老炮5 小时前
带宽估计算法(gcc++)架构设计及优化
网络·算法·webrtc
dsyyyyy11015 小时前
计数孤岛(DFS和BFS解决)
算法·深度优先·宽度优先
会编程的土豆5 小时前
01背包与完全背包详解
开发语言·数据结构·c++·算法
汀、人工智能6 小时前
[特殊字符] 第86课:最大正方形
数据结构·算法·数据库架构·图论·bfs·最大正方形