LeetCode: Partition List
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given 1->4->3->2->5->2
and x = 3,
return 1->2->2->4->3->5
.
地址:https://oj.leetcode.com/problems/partition-list/
算法:首先,找到第一个大于等于x的节点,记其前趋节点为pre,则在继续往后遍历,若发现比x小的值,则把该节点从链表中移出来,插入到pre节点后面。代码:
1 /**
2 * Definition for singly-linked list.
3 * struct ListNode {
4 * int val;
5 * ListNode *next;
6 * ListNode(int x) : val(x), next(NULL) {}
7 * };
8 */
9 class Solution {
10 public:
11 ListNode *partition(ListNode *head, int x) {
12 if(!head) return NULL;
13 ListNode *p = head;
14 ListNode *pre = NULL;
15 while(p && p->val < x){
16 pre = p;
17 p = p->next;
18 }
19 if(!p)
20 return head;
21 ListNode *q = NULL;
22 while(p->next){
23 if(p->next->val < x){
24 q = p->next;
25 p->next = q->next;
26 if(pre){
27 q->next = pre->next;
28 pre->next = q;
29 pre = q;
30 }else{
31 q->next = head;
32 head = q;
33 pre = q;
34 }
35 }else{
36 p = p->next;
37 }
38 }
39 return head;
40 }
41 };
【推荐】博客园的心动:当一群程序员决定开源共建一个真诚相亲平台
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】Flutter适配HarmonyOS 5知识地图,实战解析+高频避坑指南
【推荐】凌霞软件回馈社区,携手博客园推出1Panel与Halo联合终身会员
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 聊一聊 Linux 上对函数进行 hook 的两种方式
· C# 锁机制全景与高效实践:从 Monitor 到 .NET 9 全新 Lock
· 一则复杂 SQL 改写后有感
· golang中写个字符串遍历谁不会?且看我如何提升 50 倍
· C# 代码如何影响 CPU 缓存速度?
· 突发,CSDN 崩了!程序员们开始慌了?
· 一个基于 .NET 8 + Ant Design Blazor 开发的简洁现代后台管理框架
· C# WinForms 实现打印监听组件
· 鸿蒙Next仓颉语言开发实战教程:订单详情
· 网易游戏DB SaaS引入OceanBase:存储成本降60%,备份恢复提速3倍