您的位置:首页 > 编程语言 > C语言/C++

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的节点。

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: