问题:给定一个链表和一个值X,将链表划分成两部分,使得划分后小于X的节点在前面,大于X的节点在后。保持原顺序不变。如:给定链表:
1 7 8 2 4 3 2 5 2 0和X=3,返回:1 2 2 2 0 7 8 4 3 5
解法:分别申请两个指针p和q,小于X的添加到p中,大于等于的添加到q中,最后将q连接到p的末端即可。
扩展:可以适用于快速排序。
#include<bits/stdc++.h>
using namespace std;
struct node
{
int val;
node *next;
node(int v):val(v),next(NULL){}
};
void print(node *hea)
{
node *p=hea->next;
int f=0;
while(p)
{
if(f)
printf(" ");
printf("%d",p->val);
p=p->next;
f=1;
}
printf("\n");
}
void dt(node *T)
{
node *pn;
while(T)
{
pn=T->next;
delete T;
T=pn;
}
}
void hf(node *hea,int num)
{
node *tmp,*q=hea->next,*tail1,*tail2,*hea1,*hea2;
int k=0,k1=0;
tail1=new node(0);
tail2=new node(0);
hea1=new node(0);
while(q)
{
if(q->val>=num)
{
tmp=new node(q->val);
tail1->next=tmp;
tail1=tmp;
if(k==0)
hea1=tmp;
k=1;
}
else
{
tmp=new node(q->val);
tail2->next=tmp;
tail2=tmp;
if(k1==0)
{
tmp->next=hea2->next;
hea2->next=tmp;
}
k1=1;
}
q=q->next;
}
tail2->next=hea1;
print(hea2);
dt(hea2);
dt(hea1);
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
node *tail,*p,*hea;
int num;
hea=new node(0);
tail=new node(0);
for(int i=0;i<n;i++)
{
scanf("%d",&num);
p=new node(num);
tail->next=p;
tail=p;
if(i==0)
{
p->next=hea->next;
hea->next=p;
}
}
scanf("%d",&num);
hf(hea,num);
dt(hea);
}
return 0;
}