Time Limit: 1000 ms Memory Limit: 65536 KiB
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
Hint
不得使用数组!
Source
本题其实就是,建立三个链表,一个存储原数据,两个存储拆分数据;
#include <stdio.h>
#include <stdlib.h>
struct node
{
int a;
struct node *next;
};
int main()
{
int a,b=0,c=0,x;
int i;
scanf("%d",&a);
struct node *head1,*head2,*head3,*q,*p;
head1 = (struct node *)malloc(sizeof(struct node));
head1 -> next =NULL;
q = head1;
for(i=0; i<a; i++) //建立存储原数据链表;
{
scanf("%d",&x);
p = (struct node *)malloc(sizeof(struct node));
p -> next =NULL;
p -> a = x;
q -> next = p;
q = p;
}
head2 = (struct node *)malloc(sizeof(struct node));
head2 -> next = NULL;
head3 = (struct node *)malloc(sizeof(struct node));
head3 -> next =NULL; //同时建立两个链表;
q = head1 -> next;
struct node *p1 = head2,*p2 = head3;
while(q)
{
p = (struct node *)malloc(sizeof(struct node));
p -> next = NULL;
p -> a = q -> a; //每次建立一个节点;
if((q -> a)%2==0) //如果是偶数连接在第二个链表上;
{
b++;
p1 -> next = p;
p1 = p;
}
else //否则连接在第三个链表上;
{
c++;
p2 -> next = p;
p2 = p;
}
q = q -> next;
}
p1 = head2 -> next;
p2 = head3 -> next;
printf("%d %d\n",b,c);
while(p1) //输出;
{
if(p1 -> next)
printf("%d ",p1 -> a);
else
printf("%d\n",p1 -> a);
p1 = p1 -> next;
}
while(p2)
{
if(p2 -> next)
printf("%d ",p2 -> a);
else
printf("%d\n",p2 -> a);
p2 = p2 -> next;
}
return 0;
}