数据结构C语言习题求解……由计算机随即生产20个100以内的随机整数。(链式队列的应用)

链式队列的应用:由计算机随即生产20个100以内的随机整数。

分别建立三个链式队列Q0、Q1、Q2,分别存放能被3整除的随机数、 被3整除余1的随机数和被3整除余2的随机数。最后输出三个队列中的随机数。(需要指出每个队列的元素个数)

需要的函数:InitQueue(初始化)、EmptyQueue(是否为空)、QueueLength(队列长度)、EnQueue(进队列)、DeQueue(出队列)

第1个回答  2013-11-14
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
struct val
{
int data;
struct val *node;
};
typedef struct val li;
typedef li *lin;
lin linQ[3];
void InitQueue(); //初始化
lin EnQueue(lin lina,int data); //进队列
int EmptyQueue(lin lina); //是否为空
int QueueLength(lin lina); //队列长度
void DeQueue(lin lina,int len,int i); //出队列void main()
{
int len;
int data;
int Queue;
InitQueue();
for(len=0;len<20;len++)
{
data=rand()%100;
Queue=data%3;
if(Queue<3)
linQ[Queue]=EnQueue(linQ[Queue],data);
} for(len=0;len<3;len++)
{
data=QueueLength(linQ[len]);
if(EmptyQueue(linQ[len]))
DeQueue(linQ[len],data,len);
else
printf("NULL");
}
getch();
}
void InitQueue()
{ int len;
for(len=0;len<3;len++)
linQ[len]=NULL;
srand((unsigned int)time(NULL));
}lin EnQueue(lin lina,int data)
{
lin merory;
lin linb;
merory=(lin)malloc(sizeof(li));
merory->data=data;
merory->node=NULL;
if(!merory)
{
return NULL; } if(!lina)
{
return merory;
}
linb=lina; while(linb->node!=NULL)
linb=linb->node; linb->node=merory;
return lina;
}
int EmptyQueue(lin lina)
{
if(lina)
return 1;
return 0;
}
int QueueLength(lin lina)
{
int len=0;
lin linb;
linb=lina;
while(linb!=NULL)
{
len++;
linb=linb->node;
}
return len;
}
void DeQueue(lin lina,int len,int i)
{
lin linb;
linb=lina;
printf("A total of %d can be divided exactly by 3 more than %d random Numbers:\n\n",len,i);
while(linb!=NULL)
{
printf("%d ",linb->data);
linb=linb->node;
}
printf("\n\n");
}
第2个回答  2013-11-14
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define elemt int
typedef struct qnode{
elemt data;
struct qnode *next;
}node,*nd;
typedef struct{
nd front;
nd rear;
}lq;
lq InitQueue (void){
lq t;
t.front=t.rear=(nd )malloc(sizeof(node));
if(!t.front)
exit(0);
t.front->next=NULL;
return t;
}
lq EnQueue (lq t,elemt e){
nd p=(nd)malloc(sizeof(node));
if(!p) exit(0);
p->data =e;
p->next=NULL;
t.rear->next=p;
t.rear=p;
return t;
}
lq DeQueue (lq t){
elemt e;
nd p;
if(t.front==t.rear) exit(0);
p=t.front->next;
e=p->data;
t.front->next=p->next;
free(p);
return t;
}
int QueueLength(lq t){
int n=0;
nd p;
p=t.front;
for(;p->next!=NULL;n++){
p=p->next;
}
return n;
}void print(lq t){
nd p;
p=t.front->next;
while(p!=NULL){
printf("%d ",p->data);
p=p->next;
}
printf("\n个数为%d\n",QueueLength(t));
}
void main(){
int i=0,j;
lq Q0,Q2,Q1;
Q0=InitQueue();
Q1=InitQueue();
Q2=InitQueue();
srand((unsigned int)time(NULL));
for(;i<20;i++){
j=rand()%100;
switch(j%3){
case 0:Q0=EnQueue(Q0,j);break;
case 1:Q1=EnQueue(Q1,j);break;
case 2:Q2=EnQueue(Q2,j);break;
}
}
print(Q0);
print(Q1);
print(Q2); }本回答被网友采纳
相似回答
大家正在搜