您的位置:首页 > 其它

LeetCode---(86) Partition List

2015-05-19 20:07 465 查看
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的节点,一个用于存放值不小于x的节点。

/**
* 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) {
if(head==NULL)
return NULL;
ListNode* p=head;
ListNode* L1=new ListNode(0);
ListNode* p1=L1;
ListNode* L2=new ListNode(0);
ListNode* p2=L2;
while(p!=NULL)
{
if(p->val<x)
{
ListNode* q=new ListNode(p->val);
p1->next=q;
p1=p1->next;
}
else
{
ListNode* q=new ListNode(p->val);
p2->next=q;

99b3
p2=p2->next;
}
p=p->next;
}
p1->next=L2->next;
return L1->next;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: