摘要:单链表的拆分使用到的方法和单链表的逆置相似,下面上代码
单链表拆分的思路
1、为要拆分的子链表建立属于他们的表头
2、设立工作指针根据要求从原表中选择性插入子链
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
int main()
{
struct node *head,*p,*q,*tail;
int n,i;
scanf("%d",&n);
head=(struct node*)malloc(sizeof(struct node));
head->next=NULL;
tail=head;
for(i=1; i<=n; i++)
{
p=(struct node*)malloc(sizeof(struct node));
scanf("%d",&p->data);
p->next=NULL;
tail->next=p;
tail=p;
}
struct node *head1,*head2,*tail1,*tail2;//这里其实多建立了一个表头
//原表的表头已经空出来了,这里也可也只设置一套就可以
head1=(struct node*)malloc(sizeof(struct node));
head2=(struct node*)malloc(sizeof(struct node));
head1->next=NULL;
head2->next=NULL;
p=head->next;
q=p->next;
tail1=head1;
tail2=head2;
int num1,num2;
num1=num2=0;
while(p)
{
if(p->data%2==0)
{
p->next=NULL;//这里还是要让他指向NULL,不然建立完的链表在输出又会出问题
tail2->next=p;
tail2=p;
num2++;
}
else
{
p->next=NULL;
tail1->next=p;
tail1=p;
num1++;
}
p=q;
if(q)
q=q->next;
}
printf("%d %d\n",num2,num1);
p=head2->next;
while(p)
{
if(p->next)
printf("%d ",p->data);
else
printf("%d\n",p->data);
p=p->next;
}
p=head1->next;
while(p)
{
if(p->next)
printf("%d ",p->data);
else
printf("%d\n",p->data);
p=p->next;
}
return 0;
}