leetcode_c++:链表:Partition List (086)
2016-07-17 15:10
435 查看
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.
o(N)
题意为将小于特定值x的所有节点均放在不小于x的节点的前面,而且,不能改变原来节点的前后位置。
思路:设置两个链表,一个用于存放值小于x的节点,一个用于存放值不小于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.
o(N)
题意为将小于特定值x的所有节点均放在不小于x的节点的前面,而且,不能改变原来节点的前后位置。
思路:设置两个链表,一个用于存放值小于x的节点,一个用于存放值不小于x的节点。
class Solution { public: ListNode* partition(ListNode* head, int x) { ListNode* dummy=new ListNode(-1); dummy->next=head; ListNode* cur=dummy,* par,*rec; while(cur->next!=NULL && cur->next->val<x) cur=cur->next; par=cur; rec=cur->next; while(cur->next!=NULL){ if(cur->next->val<x){ par=(par->next=cur->next); cur->next=cur->next->next; par->next=rec; } else cur=cur->next; } return dummy->next; } };
相关文章推荐
- C++ 封装 继承 多态 (重点多态的实现)
- Single Number III
- C++ PP Chapter XI 使用类
- Rotate Image
- C++智能指针 相关知识
- C++异常处理基础
- leetcode_c++:链表:Remove Duplicates from Sorted List (083)
- 《C++ Primer Plus》第17章 输入、输出和文件 学习笔记
- cccc
- C++异常处理机制
- C++应用程序性能优化——C++语言特性
- Permutations
- Jump Game II
- L1-028. 判断素数
- [32/64]关于DLL注入与Hook(minihook)的简单介绍与使用
- 值得学习的C语言开源项目
- Leetcode 345. Reverse Vowels of a String (Easy) (cpp)
- C++ PP Chapter X 对象和类
- C++转换构造函数与类型转换构造函数
- 一种高效的 vector 四则运算处理方法