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

[leetcode] 【链表】86. Partition List

2016-05-30 16:43 387 查看
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
.

题意

给定一个值x,把链表中小于x的值放到大于等于x的值之前。即
Given 
1->4->3->2->5->2
 and 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:
ListNode* partition(ListNode* head, int x) {
ListNode small(-1);
ListNode big(-1);
auto small_p=&small;
auto big_p=&big;
for(ListNode *cur=head;cur;cur=cur->next)
{
if(cur->val<x)
{
small_p->next=cur;
small_p=cur;
}
else
{
big_p->next=cur;
big_p=cur;
}
}
big_p->next=NULL;
small_p->next=big.next;
return small.next;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode cpp