Problem Description
输入N个整数顺序建立一个单链表,将该单链表拆分成两个子链表,第一个子链表存放了所有的偶数,第二个子链表存放了所有的奇数。两个子链表中数据的相对次序与原链表一致。
Input
第一行输入整数N;;
第二行依次输入N个整数。
Output
第一行分别输出偶数链表与奇数链表的元素个数;
第二行依次输出偶数子链表的所有数据;
第三行依次输出奇数子链表的所有数据。
Sample Input
10
1 3 22 8 15 999 9 44 6 1001
Sample Output
4 6
22 8 44 6
1 3 15 999 9 1001
#include <stdio.h>
#include <stdlib.h>
typedef struct LNode *List;
struct LNode
{
int data;
List next;
};
void Print(List);
int main()
{
int n;
scanf("%d",&n);
int i;
List head;
List front;
for(i=0;i<n;i++)
{
List p=(List)malloc(sizeof(struct LNode));
p->next=NULL;
scanf("%d",&p->data);
if(i==0)
head=p;
else
front->next=p;
front=p;
}
List head1=NULL,head2=NULL;
int count1=0,count2=0;
List front1,front2;
List p=head;
int flag=-1;
while(p)
{
if(p->data%2==0)//偶数
{
flag=0;
count1++;
if(head1==NULL)
head1=p;
else
front1->next=p;
front1=p;
}
else//奇数
{
flag=1;
count2++;
if(head2==NULL)
head2=p;
else
front2->next=p;
front2=p;
}
p=p->next;
if(flag==0)
front1->next=NULL;
else if(flag==1)
front2->next=NULL;
}
printf("%d %d\n",count1,count2);
Print(head1);
Print(head2);
return 0;
}
void Print(List head)
{
List p=head;
while(p)
{
printf("%d",p->data);
if(p->next)
printf(" ");
else
printf("\n");
p=p->next;
}
}