裁判测试程序样例:
#include <stdio.h>
#include <stdlib.h>
#define ERROR -1
typedef int ElementType;
typedef enum { addq, delq, end } Operation;
typedef enum { false, true } bool;
typedef int Position;
typedef struct QNode *PtrToQNode;
struct QNode {
ElementType *Data; /* 存储元素的数组 */
Position Front; /* 队列的头、尾指针 */
int Count; /* 队列中元素个数 */
int MaxSize; /* 队列最大容量 */
};
typedef PtrToQNode Queue;
Queue CreateQueue( int MaxSize )
{
Queue Q = (Queue)malloc(sizeof(struct QNode));
Q->Data = (ElementType *)malloc(MaxSize * sizeof(ElementType));
Q->Front = 0;
Q->Count = 0;
Q->MaxSize = MaxSize;
return Q;
}
bool AddQ( Queue Q, ElementType X );
ElementType DeleteQ( Queue Q );
Operation GetOp(); /* 裁判实现,细节不表 */
int main()
{
ElementType X;
Queue Q;
int N, done = 0;
scanf("%d", &N);
Q = CreateQueue(N);
while ( !done ) {
switch( GetOp() ) {
case addq:
scanf("%d", &X);
AddQ(Q, X);
break;
case delq:
X = DeleteQ(Q);
if ( X!=ERROR ) printf("%d is out
", X);
break;
case end:
while (Q->Count) printf("%d ", DeleteQ(Q));
done = 1;
break;
}
}
return 0;
}
/* 你的代码将被嵌在这里 */
解题思路: Q->Front指向首元素位置,Q->Count作为偏移量
1 bool AddQ( Queue Q, ElementType X )
2 {
3 if(Q->Count == Q->MaxSize)
4 {
5 printf("Queue Full
");
6 return false;
7 }
8 Q->Data[(Q->Front + Q->Count) % Q->MaxSize] = X;
9 Q->Count++;
10 return true;
11 }
12 ElementType DeleteQ( Queue Q )
13 {
14 if(Q->Count == 0)
15 {
16 printf("Queue Empty
");
17 return ERROR;
18 }
19 ElementType tmp = Q->Data[Q->Front];
20 Q->Front = (Q->Front + 1) % Q->MaxSize;
21 Q->Count--;
22 return tmp;
23 }