LeetCode 86. Partition List
原题链接在这里:https://leetcode.com/problems/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
.
题解:
Two pointers, 若是当前点val比x小,就连在连到left dummy head后面。否则连到right dummy head后面.
Time Complexity: O(n). Space: O(1).
AC Java:
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 class Solution { 10 public ListNode partition(ListNode head, int x) { 11 if(head == null || head.next == null){ 12 return head; 13 } 14 15 ListNode leftDummy = new ListNode(0); //左侧dummy后面链接的点val比x小 16 ListNode rightDummy = new ListNode(0); //右侧dummy后面链接的店val比x大或者相等 17 18 ListNode leftCur = leftDummy; 19 ListNode rightCur = rightDummy; 20 while(head != null){ 21 if(head.val < x){ 22 leftCur.next = head; 23 leftCur = leftCur.next; 24 head = head.next; 25 }else{ 26 rightCur.next = head; 27 rightCur = rightCur.next; 28 head = head.next; 29 } 30 } 31 32 rightCur.next = null; //断开右侧尾节点 33 leftCur.next = rightDummy.next; 34 return leftDummy.next; 35 } 36 }
【推荐】100%开源!大型工业跨平台软件C++源码提供,建模,组态!
【推荐】AI 的力量,开发者的翅膀:欢迎使用 AI 原生开发工具 TRAE
【推荐】2025 HarmonyOS 鸿蒙创新赛正式启动,百万大奖等你挑战
【推荐】博客园的心动:当一群程序员决定开源共建一个真诚相亲平台
· 《C#高级GDI+实战:从零开发一个流程图》增加贝塞尔曲线
· AES 加密模式演进:从 ECB、CBC 到 GCM 的 C# 深度实践
· InnoDB为什么不用跳表,Redis为什么不用B+树?
· 记一次 C# 平台调用中因非托管 union 类型导致的内存访问越界
· [EF Core]聊聊“复合”属性
· 博客园众包:再次诚征3D影像景深延拓实时处理方案(预算8-15万,需求有调整)
· 扣子(Coze),开源了!Dify 天塌了
· 精选 5 款 .NET 开源、功能强大的工作流系统,告别重复造轮子!
· 从经典产品看大模型方向
· 爆肝2月,我的 AI 代码生成平台上线了!