4-16 雙端佇列 (25分)
阿新 • • 發佈:2018-12-30
#include <stdio.h> #include <stdlib.h> #include<string.h> #define ERROR -1 typedef int ElementType; #define false 0 #define true 1 typedef enum { push, pop, inject, eject, end } Operation; //typedef enum { false, true } bool; typedef int Position; typedef struct QNode *PtrToQNode; struct QNode { ElementType *Data; Position Front, Rear; int MaxSize; }; typedef PtrToQNode Deque; Deque CreateDeque( int MaxSize ) { Deque D = (Deque)malloc(sizeof(struct QNode)); MaxSize++; D->Data = (ElementType *)malloc(MaxSize * sizeof(ElementType)); D->Front = D->Rear = 0; D->MaxSize = MaxSize; return D; } bool Push( ElementType X, Deque D ); ElementType Pop( Deque D ); bool Inject( ElementType X, Deque D ); ElementType Eject( Deque D ); Operation GetOp(); void PrintDeque( Deque D ); int main() { ElementType X; Deque D; int N, done = 0; scanf("%d", &N); D = CreateDeque(N); while (!done) { switch(GetOp()) { case push: scanf("%d", &X); if (!Push(X, D)) printf("Deque is Full!\n"); break; case pop: X = Pop(D); if ( X==ERROR ) printf("Deque is Empty!\n"); else printf("%d is out\n", X); break; case inject: scanf("%d", &X); if (!Inject(X, D)) printf("Deque is Full!\n"); break; case eject: X = Eject(D); if ( X==ERROR ) printf("Deque is Empty!\n"); else printf("%d is out\n", X); break; case end: PrintDeque(D); done = 1; break; } } return 0; } bool Push( ElementType X, Deque D ) { if( (D->Rear+1)%(D->MaxSize)==D->Front) { return false; } D->Front = (((D->Front )- 1) + D->MaxSize) % D->MaxSize; D->Data[D->Front]=X; return true; } ElementType Pop( Deque D ) { ElementType X; if((D->Rear==D->Front)) return ERROR; X=D->Data[D->Front]; D->Front=((D->Front)+1)%(D->MaxSize); return X; } bool Inject( ElementType X, Deque D ) { if( ((D->Rear)+1)%(D->MaxSize)==D->Front ) { return false; } D->Data[D->Rear]=X; D->Rear=((D->Rear)+1)%(D->MaxSize); return true; } ElementType Eject( Deque D ) { ElementType X; if ( (D->Rear) == (D->Front) ) { return ERROR; } D->Rear=(((D->Rear)-1)+(D->MaxSize))%(D->MaxSize); X=D->Data[D->Rear]; return X; } Operation GetOp() { char opt[7]; scanf("%s", opt); if (strcmp(opt, "Push") == 0) { return push; } else if (strcmp(opt, "Pop") == 0) { return pop; } else if (strcmp(opt, "Inject") == 0) { return inject; } else if (strcmp(opt, "Eject") == 0) { return eject; } else if (strcmp(opt, "End") == 0) { return end; } } void PrintDeque(Deque D) { printf( "Inside Deque:" ); while (D->Front!=D->Rear ) { printf(" %d",D->Data[D->Front]); D->Front=((D->Front)+1)%(D->MaxSize); } }