循环队列
来源:互联网 发布:three.js 视角拉近 编辑:程序博客网 时间:2024/06/07 21:46
#include<iostream>#include<stdlib.h>#define MAXQSIZE 5//最大队列长度 //约定:少用一个元素空间,队满 :(Q.rear+1)%MAXQSIZE==Q.front//队空:Q.rear=Q.front using namespace std;typedef struct{ int *base; int front; int rear; }SqQueue;void InitQueue(SqQueue &Q){//构造一个空队列 Q.base=(int*)malloc(MAXQSIZE*sizeof(int)); if(!Q.base) exit(1);//存储分配失败 Q.front=Q.rear=0;}int QueueLength(SqQueue Q){ //返回Q的元素的个数 return (Q.rear-Q.front+MAXQSIZE)%MAXQSIZE; }void EnQueue(SqQueue &Q){ //插入元素e为Q的新的队尾元素 int e; cout<<"请输入要插入的元素"<<endl; cin>>e; if((Q.rear+1)%MAXQSIZE==Q.front){ cout<<"队列满"<<endl; exit(1);//队列满 } Q.base[Q.rear]=e; Q.rear=(Q.rear+1)%MAXQSIZE; }void DeQueue(SqQueue &Q,int &e){ //若队列不空,则删除Q的队头元素,用e返回其值 if(Q.front==Q.rear) exit(1);//队列空 e=Q.base[Q.front]; Q.front=(Q.front+1)%MAXQSIZE ;}void Input(SqQueue &Q){ int a,b; cout<<"请输入元素的个数"<<endl; cin>>a; if(a>MAXQSIZE-1) { cout<<"存储空间不足"<<endl; exit(1);//存储空间不足 } cout<<"请输入元素"<<endl; for(int i=0;i<a;i++){ cin>>b; Q.base[i]=b; Q.rear++; } }void OutPut(SqQueue Q){ while(Q.front!=Q.rear){ cout<<Q.base[Q.front]<<" "; Q.front=(Q.front+1)%MAXQSIZE; } cout<<endl; }int main(){ int e; SqQueue Q; InitQueue(Q); Input(Q); OutPut(Q); cout<<"删除元素"<<endl; DeQueue(Q,e); OutPut(Q); EnQueue(Q); OutPut(Q); EnQueue(Q); OutPut(Q);}
舞伴匹配
#include<stdio.h> #include<iostream>#include<stdlib.h> #define MAX 100 using namespace std;typedef struct{ char name[20]; }People; typedef struct{ People *base; int front; int rear; }SqQueue; void Init_Queue(SqQueue &s,int n){ s.base=(People *)malloc(MAX*sizeof(People)); printf("输入名字:\n"); for(int i=0;i<n;i++){ scanf("%s",&s.base[i].name); } s.front=0;s.rear=n; } void out(SqQueue &s1,SqQueue &s2,int n1,int n2){ int min; if(n1==n2) min=n1; if(n1<n2) min=n1; if(n1>n2) min=n2; for(int i=0;i<min;i++){ if(s1.front==s1.rear) s1.front=0; if(s2.front==s2.rear) s2.front=0; printf("%s--%s\n",s1.base[s1.front].name,s2.base[s2.front].name); s1.front++; s2.front++; }}void DancePartner(SqQueue &s1,SqQueue &s2,int t,int n1,int n2){//舞伴配对 int i=1; while(t){ printf("第%d轮配对为\n",i); out(s1,s2,n1,n2); printf("===================\n"); t--; i++; } } int main(){ SqQueue M,W; int m,w,times; cout<<"请输入男性人数:"<<endl; cin>>m; Init_Queue(M,m); cout<<"请输入女性人数:"<<endl; cin>>w; Init_Queue(W,w); cout<<"请输入轮次:"<<endl; cin>>times; //配对 DancePartner(M,W,times,m,w); return 0; }
阅读全文