作业帮 > 综合 > 作业

编写一道C语言题编写一个程序,功能为输入10个整数,将它们按奇、偶数分别存储在odd或even两个链表中,(两次)调用p

来源:学生作业帮 编辑:神马作文网作业帮 分类:综合作业 时间:2024/09/25 23:20:13
编写一道C语言题
编写一个程序,功能为输入10个整数,将它们按奇、偶数分别存储在odd或even两个链表中,(两次)调用print子函数以分别输出两个链表中的数据.
运行结果示例:
编写一道C语言题编写一个程序,功能为输入10个整数,将它们按奇、偶数分别存储在odd或even两个链表中,(两次)调用p
下面是我写的程序,实现你要求的功能,写得比较长,我看应该能再改得简短一点的,唉,写的时候老是有各种的错误,改了好久终于是能正常运行了,技术有待提高哪~~
#include
#include
//------------------------------------------------------------
struct odd
{
int num;
struct odd *next;
}*head_odd=NULL,*p1_odd,*p2_odd;
//p1_odd总指向最新的结点,p2_odd总指向最新结点的前面一个结点
//下面的p1_even和p2_even同理,弄两个指针是为了便于对链表进行结尾
struct even
{
int num;
struct even *next;
}*head_even=NULL,*p1_even,*p2_even;
//------------------------------------------------------------
void print(struct odd *head_odd,struct even *head_even); //函数声明
int main()
{
int k , h ; //k是用来保存输入的数,h用来记录输入了多少次
printf("请输入十个数:\n");
for(h=0 ; h0?k:-k)+2)%2!=0) //此处的条件表示当k是奇数时
{ //(k>0?k:-k)+2 这个运算是为了使负数的输入同样适用
if(head_odd!=NULL) p2_odd=p1_odd;
else p2_odd=head_odd=(struct odd *)malloc(sizeof(struct odd));
p1_odd = (struct odd *)malloc(sizeof(struct odd));
p2_odd->num = k;
p2_odd->next = p1_odd;
}
else
{
if(head_even!=NULL) p2_even=p1_even;
else p2_even=head_even=(struct even *)malloc(sizeof(struct even));
p1_even=(struct even *)malloc(sizeof(struct even));
p2_even->num = k;
p2_even->next = p1_even;
}
}
if(p2_odd!=NULL) p2_odd->next = NULL;
if(p2_even!=NULL) p2_even->next = NULL;
//加个判断条件是为了防止输入的数全部为一个类型的
print(head_odd,head_even);
getchar();
getchar(); //停留输出屏幕便于观察
return 0;
}
void print(struct odd *head_odd,struct even *head_even)
{
printf("您输入的十个数中的全部奇数为:");
for( ; head_odd != NULL ; head_odd = head_odd->next)
printf("%d ",head_odd->num);
printf("\n\n您输入的十个数中的全部偶数为:");
for( ; head_even != NULL ; head_even = head_even->next)
printf("%d ",head_even->num);
}