LeetCode 86. Partition List
来源:互联网 发布:海康威视网络配置设置 编辑:程序博客网 时间:2024/06/10 19:09
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 的移到右边去,左右两边保持原来的顺序。
看到discuss很多解法new了两个新结点分别存储左右两个链表,最后再把两个链表拼接起来,觉得这样做不是很合适,在链表中考察指针的使用的意义就没那么大了。
我的思路:
用一个指针p1指向当前待比较的结点,并用这个指针对整个链表进行一次迭代。用另一个指针p2指向左边部分链表的尾结点。
如果p1数据>x,p1移到下一个待比较结点。否则,将当前结点移到左边部分链表的尾结点后,并让它成为新的左链尾结点(p2后移),同时p1继续移到下一个待比较的结点
p1和p2一开始都是指向第一个结点,在迭代的过程中,只要还没找到第一个大于x的结点,这两者指向的结点都是相同的,不能执行上面的指针操作。所以还得先找到第一个大于x的结点。
x=3:
使用二级指针的实现:
class Solution {public: ListNode *partition(ListNode *head, int x) { if (!head) return head; ListNode **pp = &head; ListNode **partOneTail = &head; while (*pp) { if ((*pp)->val < x) { if (*pp == *partOneTail) { pp = &((*pp)->next); } else { ListNode *next = (*pp)->next; (*pp)->next = *partOneTail; *partOneTail = *pp; *pp = next; } partOneTail = &((*partOneTail)->next); } else { pp = &((*pp)->next); } } return head; }};
阅读全文
0 0
- [LeetCode]86.Partition List
- LeetCode 86. Partition List
- [Leetcode] 86. Partition List
- LeetCode --- 86. Partition List
- [leetcode] 86.Partition List
- [leetcode] 86. Partition List
- [LeetCode]86. Partition List
- 86. Partition List LeetCode
- Leetcode 86. Partition List
- LeetCode *** 86. Partition List
- LeetCode 86. Partition List
- [LeetCode]86. Partition List
- LeetCode 86. Partition List
- leetcode 86. Partition List
- Leetcode 86. Partition List
- LeetCode-86.Partition List
- [Leetcode]86. Partition List
- LeetCode - 86. Partition List
- Android Camera 系统架构源码分析(3)---->Camera的显示流程
- Apache 与 Nginx 比较
- 静态库与动态库
- LeetCode-714:Best Time to Buy and Sell Stock with Transaction Fee (带有抛售费用的股票最大利润) -- medium
- php判断图片是否显示完全的方式---图片损坏
- LeetCode 86. Partition List
- ArcEngine创建IFeature的三种方法
- dede常用数据库相关命令
- Quartz两个定时任务的配置
- 从 HTTP 到 HTTPS 再到 HSTS
- LeetCode 206. Reverse Linked List && 92. Reverse Linked List II
- 阿里云 CDN HTTPS 最佳实践——OCSP Stapling(四)
- 报错:1130-host ... is not allowed to connect to this MySql server 开放mysql远程连接 不使用localhost
- VS2010+Qt4调试时监视窗口部分类型变量只显示地址不显示值