LeetCode#86 Partition List (week4)
来源:互联网 发布:2017程序员笔记本推荐 编辑:程序博客网 时间:2024/06/07 06:21
week4(problem2)
题目
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.
原题地址:https://leetcode.com/problems/partition-list/description/
解析
题目给定一个链表,链表节点定义如下
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */
将所有比给定x小的节点移动到所有大于等于x的节点的前面。
大致思路为用两个队列存放需要移动和不需要移动的节点的数值,构造新的链表时先存放所有需要移动的节点再存放不需移动的节点,得到的新链表即为答案。
易错点解析
while (!Move.empty()) { temp2 = new ListNode(Move.front()); Move.pop(); if (isHead) { result = temp2; isHead = false; } temp2 = temp2->next; }
如上代码,在两次以上的循环中,temp2所new的节点并不是上一个节点的next,最终得到的节点并没有连接起来,这大概是像作者这种菜鸟所犯的常见错误,正确的做法如下面所示的代码。
代码
class Solution {public: ListNode* partition(ListNode* head, int x) { if (head == NULL) { return NULL; } queue<int> Original; queue<int> Move; ListNode* temp = head; while (temp != NULL) { if (temp->val < x) { Move.push(temp->val); } else { Original.push(temp->val); } temp = temp->next; } ListNode *temp2; ListNode *result; /*记录当前构造的节点是否为头节点*/ bool isHead = true; while (!Move.empty()) { if (isHead) { temp2 = new ListNode(Move.front()); Move.pop(); result = temp2; isHead = false; } else { temp2->next = new ListNode(Move.front()); Move.pop(); temp2 = temp2->next; } } while (!Original.empty()) { if (isHead) { temp2 = new ListNode(Original.front()); Original.pop(); result = temp2; isHead = false; } else { temp2->next = new ListNode(Original.front()); Original.pop(); temp2 = temp2->next; } } return result; }};
阅读全文
0 0
- LeetCode#86 Partition List (week4)
- 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
- 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
- Docker中安装OpenvSwitch 附rpm文件下载
- spring boot项目实战:redis
- Go语言 channel详解
- 工作中遇到的问题总结
- Scala(2)-类
- LeetCode#86 Partition List (week4)
- 2017 ACM-ICPC 亚洲区(西安赛区)网络赛 B Coin(逆元,费马小定理)
- Dropout和Batch Normalization的差别
- Codeforces 230D Planets【思维+SPFA】
- Android 广播的生命周期
- Hadoop安装教程链接参考
- CSDN博客配置 添加邮箱
- UVa512 Spreadsheet Tracking
- 五行