86. Partition List
来源:互联网 发布:手机怎么设置4g网络 编辑:程序博客网 时间:2024/06/01 08:44
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.
思路:开始想着如何在一个链表上实现,后来参考别人的发现没有必要,重新建两个链表就可以了,一个存大的,一个存小的。或者重新建一个新的,另外一个在原来的基础上删除。
还有一种思路是找到第一个大于等于x的,对于后面所有的小于x都插到它前面。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* partition(ListNode* head, int x) { if(head==NULL || head->next==NULL) { return head; } ListNode* bigList = new ListNode(-1); ListNode* fakeHead = new ListNode(-1); fakeHead->next = head; ListNode* pre = fakeHead; ListNode* preBig = bigList; while(head!=NULL) { if(head->val >= x) { pre->next = head->next; preBig->next = head; preBig = preBig->next; preBig->next = NULL; head = pre->next; } else { pre = pre->next; head = head->next; } } preBig->next = NULL; pre->next = bigList->next; return fakeHead->next; }};
0 0
- [LeetCode]86.Partition List
- LeetCode 86. Partition List
- [Leetcode] 86. Partition List
- LeetCode --- 86. Partition List
- 86. Partition List
- [leetcode] 86.Partition List
- [leetcode] 86. Partition List
- 86. Partition List
- [LeetCode]86. Partition List
- 86. Partition List
- 86. Partition List LeetCode
- 86. Partition List
- 86. Partition List
- 86. Partition List
- Leetcode 86. Partition List
- LeetCode *** 86. Partition List
- LeetCode 86. Partition List
- [LeetCode]86. Partition List
- java SAX
- android学习日志--View中的onMeasure
- Qt学习之路(28): 坐标变换
- Triangulation by Ear Clipping(耳切法处理多边形三角划分)
- 怎样才能叫高级程序员?
- 86. Partition List
- C#HttpClient或使用CookieContainer模拟登陆后HttpRequest不发送cookie的解决方法及原因
- 图文并茂用地址分析双向链表
- robot framework 自定义关键字详细过程及debug。
- 文件较复杂操作: 打包、解压
- [Java]知乎下巴第0集:让我们一起来做一个知乎爬虫吧哦耶
- Fork/Join框架之双端队列
- c预处理命令
- QSignalMapper 使用方法 参见QSignalMapper中使用文档