创建随机数链表

编写自定义函数:建立一个带有头结点head的有20个结点的链表,20个结点所需数值由随机数产生。
编写自定义函数:建立两个链表,把存有数据的链表中的偶数存入一个链表,奇数存入另一个链表中。
编写主函数调用上述两个函数并可输出三个链表中的数据。

完整的代码如下:

#include "iostream" using namespace std; #include "time.h" struct node { int data; node *next; }; node *head=NULL; void InsertNode(node* &head,int value) { if(head==NULL) { head=(node *)malloc(sizeof(node)); if(head==NULL) { printf("malloc failed"); return ; } else { head->data=value; head->next=NULL; } } else { node *temp=(node *)malloc(sizeof(node)); if(temp==NULL) { printf("malloc failed"); return ; } else { temp->data=value; temp->next=head; head=temp; } } return ; } void Insert(int n) { srand( (unsigned)time( NULL ) ); //初始化随机数 for(int i=0;i<n;i++) InsertNode(head,rand()); node *p=(node *)malloc(sizeof(node)); p->next=head; head=p; printf("所有的随机数为: "); p=head->next; //输出测试 while(p) { printf("%d ",p->data); p=p->next; } printf("/n/n"); return ; } void odd_even() { node *p=head->next; node *head_odd,*head_even,*q,*t; head_odd=NULL; head_even=NULL; while(p) { if(p->data%2==0) { if(head_even==NULL) { head_even=(node *)malloc(sizeof(node)); if(head_even==NULL) { printf("malloc failed"); return ; } else { head_even->data=p->data; head_even->next=NULL; q=head_even; } } else { node *temp=(node *)malloc(sizeof(node)); if(temp==NULL) { printf("malloc failed"); return ; } else { temp->data=p->data; q->next=temp; temp->next=NULL; q=q->next; } } } else { if(head_odd==NULL) { head_odd=(node *)malloc(sizeof(node)); if(head_odd==NULL) { printf("malloc failed"); return ; } else { head_odd->data=p->data; head_odd->next=NULL; t=head_odd; } } else { node *temp=(node *)malloc(sizeof(node)); if(temp==NULL) { printf("malloc failed"); return ; } else { temp->data=p->data; t->next=temp; temp->next=NULL; t=t->next; } } } p=p->next; } q=head_even; t=head_odd; printf("其中偶数为: "); while(q) { printf("%d ",q->data); q=q->next; } printf("/n/n"); printf("其中奇数为: "); while(t) { printf("%d ",t->data); t=t->next; } printf("/n/n"); } int main(void) { Insert(20); odd_even(); system("pause"); return 0; }

运行的结果如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值