数据结构C语言习题求解……由计算机随即生产20个100以内的随机整数。(链式队列的应用)
发布网友
发布时间:2022-05-06 02:06
我来回答
共2个回答
热心网友
时间:2023-10-10 16:13
#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");
}
热心网友
时间:2023-10-10 16:13
#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); }