数据结构作业-第三章-队列

环形队列

内容: 设从键盘输入一序列的字符a1,a2,...an.设计一个算法实现这样的功能:若ai为数字字符,ai进队;若ai为小写字符,将队首元素出队;若ai为其他字符,表示输入结束要求使用环形队列

huanxing.cpp

某位室友大佬写的
#include <stdio.h>
#include <stdlib.h>

#define N 48

typedef struct {
	char d[N];
	int h;
	int e;
}Queue;

void init(Queue*& q);
bool isEmpty(Queue* q);
void freeQueue(Queue*&);
bool en(Queue*, char);
char de(Queue*);

int main()
{
	Queue* q;
	init(q);
	char c;
	while (true) {
		c = getchar();
		if (c >= '0' && c <= '9') {
			en(q, c);
			printf("%c>", c);
		}
		else if (c >= 'a' && c <= 'z') {
			if (!isEmpty(q)) {
				printf("%c<", de(q));
			}
		}
		else {
			break;
		}
	}
	freeQueue(q);
	return 0;
}

void init(Queue*& q)
{
	q = (Queue*)malloc(sizeof(Queue));
	q->h = q->e = -1;
}
bool isEmpty(Queue* q)
{
	return q->h == q->e;
}
void freeQueue(Queue*& q)
{
	free(q);
	q = NULL;
}
bool en(Queue* q, char c)
{
	if ((q->h + 1) % N == q->e) {
		return false;
	}
	else {
		q->h = (q->h + 1) % N;
		q->d[q->h] = c;
	}
}
char de(Queue* q)
{
	q->e = (q->e + 1) % N;
	return q->d[q->e];
}

运行结果

原文地址:https://www.cnblogs.com/DTsec/p/15492571.html