PTA 6-3 另类循环队列

记录 循环队列顺序表示 另类循环队列 中国民航大学数据结构作业题

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#define ERROR -1
typedef int ElementType;
typedef enum { addq, delq, end } Operation;
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(){ /* 裁判实现,细节不表 */
	char c[10];
	scanf("%s",c);
	if(!strcmp("Add",c)) return addq;
	if(!strcmp("Del",c)) return delq;
	if(!strcmp("End",c)) return end;
}

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;
}

/* 你的代码将被嵌在这里 */
bool AddQ( Queue Q, ElementType X ){
	if(Q->Count==Q->MaxSize){
		printf("Queue Full\n");
		return false;
	}
	else{		
		if(Q->Front==Q->MaxSize){
			Q->Front=0;
		}
		Q->Data[Q->Front++]=X;
		Q->Count++;
	}
}
ElementType DeleteQ( Queue Q ){
	int X;
	if(Q->Count==0){
		printf("Queue Empty\n");
		return -1;
	}
	else{
		if(Q->Front==0){
			X=Q->Data[Q->Front];
			Q->Count--;
			Q->Front=Q->MaxSize;
			return X;
		}
		else{
		X=Q->Data[(Q->Front-Q->Count+Q->MaxSize)%Q->MaxSize];
		Q->Count--;
		return X;
		}
	}
}

对于初学者需要理解循环队列的顺序表示 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值