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.
第一种方法:
class Solution {
public:
ListNode* partition(ListNode* head, int x)
{
ListNode* dummy=new ListNode(-1);
dummy->next=head;
ListNode *s,*p;
s=dummy;
while(s->next&&s->next->val<x)//先把前面的小于target的跳过
s=s->next;
p=s;
while(p->next)
{
if(p->next->val<x)
{
ListNode *q=p->next;//取出小于target的
p->next=q->next;
q->next=s->next;
s->next=q;//将其插在s后面
s=s->next;//s想后移,以便插入下一个q
}
else
p=p->next;//大于target直接向后移动
}
return dummy->next;
}
};
第二种方法
class Solution {
public:
ListNode* partition(ListNode* head, int x)
{
ListNode* front=new ListNode(-1);
front->next=NULL;//front后面接的是小于target的元素
ListNode *p=front;
ListNode *back=new ListNode(-1);//back后面接的是大于target的元素
back->next=head;
ListNode *q=back;
while(q->next)//取出head中小于target的插入front中,剩下的留在back中
{
if(q->next->val>=x)
q=q->next;
else
{
ListNode *s=q->next;
q->next=s->next;
p->next=s;
p=s;
}
}
p->next=back->next;//front和back拼接在一起
return front->next;
}
};