作者:小 琛
欢迎转载,请标明出处
题目:
思路分析:
要将链表以x为基准分割,可以就是否大于x为判断法则,开辟两个新的链表head1和head2,在保证顺序不变的情况下,最后将两个链表合并。
技巧1:可以先遍历链表一遍,找到该链表是否含有x,得到其数量
技巧2:创立得链表可以是带头得,方便操作,返回得时候将头去掉即可
class Partition {
public:
ListNode* buynewnode(int x)
{
ListNode* newnode=(ListNode*)malloc(sizeof(ListNode));
newnode->val=x;
newnode->next=NULL;
return newnode;
}
void pushback(ListNode** pphead,int x)
{
ListNode* newnode=buynewnode(x);
if ((*pphead)==NULL)
{
(*pphead)=newnode;
}
else{
ListNode* tail=(*pphead);
while (tail->next!=NULL)
tail=tail->next;
tail->next=newnode;
}
}
ListNode* partition(ListNode* pHead, int x) {
if (pHead==NULL||pHead->next==NULL)
return pHead;
ListNode* cur=pHead;
ListNode* head1=(ListNode*)malloc((sizeof(ListNode)));
ListNode* head2=(ListNode*)malloc((sizeof(ListNode)));
ListNode* tail1=NULL;
ListNode* tail2=NULL;
int count=0;
while (cur!=NULL)
{
if (cur->val==x)
count++;
cur=cur->next;
}
if (count==0)
{
head1->next=NULL;
head2->next=NULL;
}
else{
tail1=head1;
tail2=head2;
head1->next=NULL;
while (count)
{
tail2->next=buynewnode(x);
tail2=tail2->next;
}
}
cur=pHead;
while (cur!=NULL)
{
if (cur->val<x)
{
pushback(&tail1,cur->val);
cur=cur->next;
tail1=tail1->next;
}
else if(cur->val>x)
{
pushback(&tail2,cur->val);
cur=cur->next;
tail2=tail2->next;
}
else
cur=cur->next;
}
if (head1->next==NULL)
return head2->next;
else if (head2->next==NULL)
return head1->next;
else{
tail1->next=head2->next;
return head1->next;
}
}
};