题目描述:
n个人从左向右编号1~n,然后从左向右报数“1,2,1,2,1,2...” 数到1的人出队,数到2的人立即站到队列的最右端继续报数,直到所有人出列。
思路:
编写进队出队函数,先依次进队,然后遍历,一次出队一个元素,用count 记录报数是否为偶数,如果是则进行入队,否则输出,因为count从1开始,这里可保证输出的奇数在入队的偶数前,注意只有为偶数了才会执行进队操作,后续会退出STL实现.......
代码展示:
#include<bits/stdc++.h>
using namespace std;
#define MaxSize 1000
typedef int ElemType;
typedef struct{ElemType data[MaxSize];int front,rear;
}SqQueue;//初始化
void InitQueue(SqQueue* &q){q=(SqQueue*)malloc(sizeof(SqQueue));q->front=q->rear=0;
}
//进队
bool enQueue(SqQueue* &q,ElemType e){if((q->rear+1)%MaxSize==q->front)return false;q->rear=(q->rear+1)%MaxSize;q->data[q->rear]=e;
}
//出队
bool chuQueue(SqQueue* &q,ElemType &e){if(q->front==q->rear)return false;q->front=(q->front+1)%MaxSize;e=q->data[q->front];return true;
}
//判断队列是否为空
bool iSNullQueue(SqQueue* q){return q->front==q->rear;
}
//销毁队列
void DestroyQueue(SqQueue* &q)
{free(q);
}
//报数函数
void baoshu(int n){int i,count=1;SqQueue *q;InitQueue(q);for(i=1;i<=n;i++){enQueue(q,i);}while(!iSNullQueue(q)){chuQueue(q,i);if(count%2==0){enQueue(q,i);}else{cout<<i<<" ";}count++;}cout<<" ";DestroyQueue(q);
}//主函数
int main()
{int n;cout<<"请输入报数人数:"<<endl;cin>>n;baoshu(n);
}
效果图:















![[Anaconda学习]本地查看代理ip,anaconda挂代理](https://img-blog.csdnimg.cn/20201225120837941.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2l0X0xpQ2hlbmd3ZWk=,size_16,color_FFFFFF,t_70)




