2013.12.26 22:58
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
.
Solution:
This is a reversed process of merging two lists. Do it in one pass and watch out for nullptr.
Time complexity is O(n), space complexity is O(1).
Accepted code:
1 // 2RE, 1AC, always keep an eye out for nullptr! 2 /** 3 * Definition for singly-linked list. 4 * struct ListNode { 5 * int val; 6 * ListNode *next; 7 * ListNode(int x) : val(x), next(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 ListNode *partition(ListNode *head, int x) { 13 // IMPORTANT: Please reset any member data you declared, as 14 // the same Solution instance will be reused for each test case. 15 ListNode *l1 = nullptr, *l2 = nullptr; 16 ListNode *h1 = nullptr, *h2 = nullptr; 17 18 while(head != nullptr){ 19 if(head->val < x){ 20 if(h1 == nullptr){ 21 h1 = l1 = head; 22 }else{ 23 l1->next = head; 24 l1 = l1->next; 25 } 26 head = head->next; 27 l1->next = nullptr; 28 }else{ 29 if(h2 == nullptr){ 30 h2 = l2 = head; 31 }else{ 32 l2->next = head; 33 l2 = l2->next; 34 } 35 head = head->next; 36 l2->next = nullptr; 37 } 38 } 39 // 2RE here, note that h1 and h2 may be empty! 40 if(h1 == nullptr){ 41 return h2; 42 }else if(h2 == nullptr){ 43 return h1; 44 } 45 l1->next = h2; 46 head = h1; 47 48 return head; 49 } 50 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)