Skip to content

Instantly share code, notes, and snippets.

@tinylamb
Last active August 29, 2015 13:56
Show Gist options
  • Select an option

  • Save tinylamb/9228640 to your computer and use it in GitHub Desktop.

Select an option

Save tinylamb/9228640 to your computer and use it in GitHub Desktop.
ADT Queue.循环队列
/*
* =========================================================
* Filename: throwcards.c
* Description: google Throwing cards away I
* 题目大意:给n张牌,放成一叠,从上到下编号从1到n,当至少还有两张牌时
* 丢弃最上面的牌,然后把新的最上面的牌放到最下面,一直重复,直到只剩下一张牌
* 输出丢弃牌的序列。
* =========================================================
*/
#include <stdio.h>
#include <stdbool.h>
#include <assert.h>
#define MAX 51 //预先知道数组最大值,留一个空来区别空/满
/*数据集定义*/
typedef struct Queue{
int array[MAX];
int head,tail;
}Queue;
/*queue上的基本操作*/
void InitQueue(Queue *q);
bool IsEmpty(Queue *q);
bool IsFull(Queue *q);
void InQueue(Queue *q,int e);
int DeQueue(Queue *q);
int main(){
int n;
int discards[MAX];
Queue q;
while(scanf("%d",&n)!=EOF && n){
InitQueue(&q);
int i;
for(i=1;i<=n;i++)
InQueue(&q,i);
int k=0;
while(!IsEmpty(&q)){
discards[k++]=DeQueue(&q);
int top=DeQueue(&q);
InQueue(&q , top);
}
printf("Discarded cards:");
for(i=0;i<n-1;i++)
printf("%d%s",discards[i],(i==n-2)?"\n":",");
printf("Remaining card:%d\n",discards[i]);
}
return 0;
}
void InitQueue(Queue *q){
q->head=q->tail=0;
}
bool IsEmpty(Queue *q){
return (q->head==q->tail)?true:false;
}
bool IsFull(Queue *q){
return ((q->tail + 1) % MAX == q->head)?true:false;
}
void InQueue(Queue *q,int e){
assert(!IsFull(q));
q->array[q->tail]=e;
q->tail = (q->tail+1) % MAX;
}
int DeQueue(Queue *q){
assert(!IsEmpty(q));
int e=q->array[q->head];
q->head = (q->head + 1) % MAX;
return e;
}
@tinylamb
Copy link
Copy Markdown
Author

循环数组队列

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment