Partition List
2016-05-25 17:20
232 查看
描述
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.
partition_list.h
下面为leetcode实现的代码:
《完》
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.
partition_list.h
#include <iostream> #include <assert.h> #include <stdlib.h> using namespace std; typedef struct ListNode { int _val; ListNode *_next; ListNode(int x) : _val(x), _next(NULL) {} }node,*node_p; class Solution { public: node_p partition(node_p &list,int x) { //参数检查 if(list==NULL) return NULL; node dummy(-1); node_p head=&dummy; head->_next=list; node_p first=head; //找_val为x的结点 node_p node_x=list; while(node_x!=NULL && node_x->_val!=x){ node_x=node_x->_next; first=first->_next; } if(node_x==NULL){ cout<<"not find node_x!"<<endl; return list; } node_p prev=node_x; node_p tmp=node_x->_next; while(tmp){ if(tmp->_val<x){ prev->_next=tmp->_next; tmp->_next=node_x; first->_next=tmp; first=first->_next; tmp=node_x->_next; }else{ tmp=tmp->_next; prev=prev->_next; } } return head->_next; } //构造一个链表 node_p create_list(int *array,int size) { assert(array); node dummy(-1); node_p prev=&dummy; node_p head=prev; for(int i=0;i<size;++i){ node_p Node=new node (array[i]); prev->_next=Node; prev=prev->_next; } return head->_next; } };partition_list.cpp
#include "partition_list.h" using namespace std; int main() { int array[]={1,4,3,2,5,2}; Solution s1; node_p list=s1.create_list(array,sizeof(array)/sizeof(array[0])); node_p newlist=s1.partition(list,4); node_p tmp=newlist; while(tmp){ cout<<tmp->_val<<" "; free(tmp); tmp=tmp->_next; } cout<<endl; return 0; }运行结果:
下面为leetcode实现的代码:
《完》
相关文章推荐
- C#中Ilist与list的区别小结
- 巧妙利用PARTITION分组排名递增特性解决合并连续相同数据行
- C#中IList<T>与List<T>的区别深入解析
- C#对list列表进行随机排序的方法
- Vc++ 控件List Control用法总结
- C++实现的泛型List类分享
- C#使用IComparer自定义List类实现排序的方法
- C# Datagridview绑定List方法代码
- javascript radio list的实现细节(多浏览器兼容)
- c++ STL容器总结之:vertor与list的应用
- SQLServer中Partition By及row_number 函数使用详解
- java实现List中对象排序的方法
- 大家注意vector, list, set, map成员函数erase
- ASP.NET―001:GridView绑定List、页面返回值具体实现
- List all the Databases on a SQL Server
- js Map List 遍历使用示例
- Java比较两个List的值是否相等的方法
- Java List双击事件实现方法
- velocity显示List与Map的方法详细解析
- 关于STL中list容器的一些总结