数据结构实验之链表五:单链表的拆分
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
输入N个整数顺序建立一个单链表,将该单链表拆分成两个子链表,第一个子链表存放了所有的偶数,第二个子链表存放了所有的奇数。两个子链表中数据的相对次序与原链表一致。
输入
第一行输入整数N;;
第二行依次输入N个整数。
输出
第一行分别输出偶数链表与奇数链表的元素个数;
第二行依次输出偶数子链表的所有数据;
第三行依次输出奇数子链表的所有数据。
示例输入
10
1 3 22 8 15 999 9 44 6 1001
示例输出
4 6
22 8 44 6
1 3 15 999 9 1001
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *creat(int n)//顺序建表
{
struct node *head,*p,*tail;
int i;
head=(struct node *)malloc(sizeof(struct node));
head->next=NULL;
tail=head;
for(i=0; i<n; i++)
{
p=(struct node *)malloc(sizeof(struct node));
scanf("%d",&p->data);
p->next=NULL;
tail->next=p;
tail=p;
}
return head;
};
int main()
{
int n,num1=0,num2=0;
struct node *head,*p,*p1,*p2,*tail2,*tail1,*head1,*head2;
scanf("%d",&n);
head=creat(n);
head1=(struct node *)malloc(sizeof(struct node));
head2=(struct node *)malloc(sizeof(struct node));
head1->next=NULL;
head2->next=NULL;//定义两个头结点
p=head->next;
tail1=head1;
tail2=head2;
while(p!=NULL)
{
if(p->data%2==0)//若p->data的数值是偶数,则放进链表1中,否则就放进链表2中
{
p1=(struct node *)malloc(sizeof(struct node));
p1->data=p->data;
p1->next=NULL;
tail1->next=p1;
tail1=p1;
num1++;
}
else
{
p2=(struct node *)malloc(sizeof(struct node));
p2->data=p->data;
p2->next=NULL;
tail2->next=p2;
tail2=p2;
num2++;
}
p=p->next;
}
printf("%d %d\n",num1,num2);//分别输出链表1和链表2中数的个数
p=head1->next;
while(p!=NULL)
{
if(p->next!=NULL)
printf("%d ",p->data);
else
printf("%d\n",p->data);
p=p->next;
}
p=head2->next;
while(p!=NULL)
{
if(p->next!=NULL)
printf("%d ",p->data);
else
printf("%d\n",p->data);
p=p->next;
}
return 0;
}