1. 程式人生 > >另類迴圈佇列

另類迴圈佇列

裁判測試程式樣例:

#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\n", 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\n");
 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\n");
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 }