2014-03-18 02:27
题目:将一个单链表按照一个值X分为两部分,小于X的部分放在大于等于X的部分之前。
解法:按照值和X的大小,分链表为两条链表,然后连起来成一条。
代码:
1 // 2.4 Write code to partition a linked list around a value x, such that all nodes less than x comes before all nodes greater than or equal to x. 2 #include <cstdio> 3 using namespace std; 4 5 struct ListNode { 6 int val; 7 ListNode *next; 8 ListNode(int x): val(x), next(nullptr) {}; 9 }; 10 11 class Solution { 12 public: 13 ListNode* partitionList(ListNode *head, int x) { 14 if (head == nullptr) { 15 return head; 16 } 17 18 ListNode *h1, *t1, *h2, *t2; 19 ListNode *ptr; 20 21 h1 = t1 = nullptr; 22 h2 = t2 = nullptr; 23 ptr = head; 24 while (ptr != nullptr) { 25 if (ptr->val < x) { 26 if (h1 == nullptr) { 27 h1 = t1 = ptr; 28 } else { 29 t1->next = ptr; 30 t1 = t1->next; 31 } 32 ptr = ptr->next; 33 t1->next = nullptr; 34 } else { 35 if (h2 == nullptr) { 36 h2 = t2 = ptr; 37 } else { 38 t2->next = ptr; 39 t2 = t2->next; 40 } 41 ptr = ptr->next; 42 t2->next = nullptr; 43 } 44 } 45 if (h1 == nullptr) { 46 return h2; 47 } else if (h2 == nullptr) { 48 return h1; 49 } else { 50 t1->next = h2; 51 return h1; 52 } 53 } 54 }; 55 56 int main() 57 { 58 int i; 59 int n, x; 60 int val; 61 struct ListNode *head, *ptr; 62 Solution sol; 63 64 while (scanf("%d", &n) == 1 && n > 0) { 65 // create a linked list 66 ptr = head = nullptr; 67 for (i = 0; i < n; ++i) { 68 scanf("%d", &val); 69 if (head == nullptr) { 70 head = ptr = new ListNode(val); 71 } else { 72 ptr->next = new ListNode(val); 73 ptr = ptr->next; 74 } 75 } 76 77 // partition the list around value x. 78 scanf("%d", &x); 79 head = sol.partitionList(head, x); 80 81 // print the list 82 printf("%d", head->val); 83 ptr = head->next; 84 while (ptr != nullptr) { 85 printf("->%d", ptr->val); 86 ptr = ptr->next; 87 } 88 printf("\n"); 89 90 // delete the list 91 while (head != nullptr) { 92 ptr = head->next; 93 delete head; 94 head = ptr; 95 } 96 } 97 98 return 0; 99 }
【推荐】国内首个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新功能体验(一)