[Leetcode]Partition List
2015-10-23 12:51
375 查看
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
return
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/*algorithm two pointers
create a list l to store the value < x
scan the list, remove those element < x to l
link l with old list
time O(n) space O(1)
*/
ListNode* partition(ListNode* head, int x) {
ListNode dummy(0),*p,*prev,*l,*tail;
dummy.next = head;
prev = &dummy,p = head;
l = tail = NULL;
while(p){
if(p->val < x){
prev->next = p->next;
if(!l)l = tail = p;
else {
tail->next = p;
tail = tail->next;
}
p = prev->next;
}else{
prev = p;
p = p->next;
}
}
if(l)tail->next = dummy.next;
else l = dummy.next;
return l;
}
};
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->2and x = 3,
return
1->2->2->4->3->5.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/*algorithm two pointers
create a list l to store the value < x
scan the list, remove those element < x to l
link l with old list
time O(n) space O(1)
*/
ListNode* partition(ListNode* head, int x) {
ListNode dummy(0),*p,*prev,*l,*tail;
dummy.next = head;
prev = &dummy,p = head;
l = tail = NULL;
while(p){
if(p->val < x){
prev->next = p->next;
if(!l)l = tail = p;
else {
tail->next = p;
tail = tail->next;
}
p = prev->next;
}else{
prev = p;
p = p->next;
}
}
if(l)tail->next = dummy.next;
else l = dummy.next;
return l;
}
};
相关文章推荐
- 大型网站核心的架构(6-1)基本要素
- Bootstrap 学习(1)
- Redis学习笔记十五、实例代码
- poj 3984 迷宫问题..
- 微信开发(一):用JSAPI做微信支付+微信卡包(代金券)
- Redis学习笔记十四、内存优化
- C++多级指针的”解引用“
- Linux---用户和用户组
- Redis学习笔记十三、服务器管理
- 值得学习的博客
- 个人网站及无备案网站将无法得到腾讯认证
- codevs1959拔河比赛[三星~]
- HDU 1557 权利指数 国家压缩 暴力
- windows server 2008 r2, 每隔一段时间自动关机
- Redis学习笔记十二、管线
- 2015年奇虎360服务器开发C++电话面试问题
- Java/Android中的函数调用&回调函数&自定义回调函数
- 美河在线
- Win32 Windows规划 三
- Redis学习笔记十一、虚拟内存