86. Partition List
来源:互联网 发布:2017网络作家排行榜 编辑:程序博客网 时间:2024/06/03 12:43
这道题要求我们划分链表,把所有小于给定值的节点都移到前面,大于该值的节点顺序不变。
设定三个指针,pre,cur和tmp。首先把所有小于x的值跳过去,再遇到新的小于x的数就从这个位置连接。pre首先指向1。然后令cur指向pre,就从pre这里开始往后找。遇到next大于等于x的跳过,那么cur指的就是3,tmp指向2暂停,这时候要把2节点接到pre后面。然后cur再继续往后遍历。
/** * 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) { ListNode* newhead = new ListNode(-1); newhead->next = head; ListNode *pre = newhead; while(pre->next && pre->next->val < x) pre = pre->next; ListNode *cur = pre; while(cur->next){ if(cur->next->val < x){ ListNode* tmp = cur->next; cur->next = tmp->next; tmp->next = pre->next; pre->next = tmp; pre = pre->next; }else{ cur = cur->next; } } return newhead->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
- 证券行业基础知识(二)
- 【JZOJ5428】【NOIP2017提高A组集训10.27】查询
- BZOJ 4881 [Lydsy2017年5月月赛] 二分图染色+线段树
- 利用Swig在python中调用C/C++代码
- python基础学习小结(1)
- 86. Partition List
- 生成时间段不交叉的数据。
- Java多线程知识点
- Keras 可视化无法使用的解决方案
- 求1*2*3*...*n的值并把各项相加
- 1031 UVA540 map+queue
- Putty常见错误汇总
- 反射
- 单调队列