86-partition list
来源:互联网 发布:数据录入查询系统源码 编辑:程序博客网 时间:2024/06/05 19:04
难度:medium
类别:linked list
1.题目描述
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.
2.算法分析
遍历一遍链表,将比x小的数值压到一个队列中,比x大或者等于x的压到另外一个队列中。
创建新的链表,从存小值的队列开始创建,创建完了以后再讲大值得队列中的值添加到新的链表中。
3.代码实现
ListNode* partition(ListNode* head, int x) { if (head == NULL || head->next == NULL) return head; queue<int> smaller, bigger; while (head != NULL) { if (head->val < x) { smaller.push(head->val); } else { bigger.push(head->val); } head = head->next; } ListNode* result = NULL; if (!smaller.empty()) { result = new ListNode(smaller.front()); head = result; smaller.pop(); } else { result = new ListNode(bigger.front()); head = result; bigger.pop(); } while (!smaller.empty()) { result->next = new ListNode(smaller.front()); smaller.pop(); result = result->next; } while (!bigger.empty()) { result->next = new ListNode(bigger.front()); bigger.pop(); result = result->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 86 Partition List
- Leetcode[86]-Partition List
- 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
- 正则式分段提取中文,看不懂啊,先记录下来
- 最小费用流模板(Bellman-Ford算法找最短路)
- 短视频sdk:选择一个靠谱的短视频SDK 你需要了解这些
- certbot-auto 生成nginx证书指定nginx配置路径
- Matlab 文件路径总结
- 86-partition list
- 2017.11.3 队测T2 death
- JavaScripts中的this指向及call、apply详解
- 算法修炼网站
- hdu 3949(线性基模版) 异或和中第k小的数
- Excel对比两行数据是否相同?
- gradle 打jar包上传maven仓储
- 计算机为什么用二进制存储数据?即为什么是0101010,为什么不用其他进制?既然计算机是二进制,为什么又衍生出来一八进制、十六进制干什么,八进制和十六进制在计算机中有什么用呢?
- 堆和队列