欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

基础实验3-2.5-堆栈模拟队列-函数题

程序员文章站 2022-03-13 16:02:06
...

基础实验3-2.5-堆栈模拟队列-函数题

解题代码

#include<stdio.h>
#include<stdlib.h>
typedef struct stack* Stack;
struct stack {
	int *data;
	int top;
	int MaxSize;
};
int IsFull(Stack S) {
	return S->top == S->MaxSize - 1 ? 1 : 0;
}
int IsEmpty(Stack S) {
	return S->top == -1 ? 1 : 0;
}
void Push(Stack S, int item) {
	S->data[++S->top] = item;
}
int Pop(Stack S) {
	return S->data[S->top--];
}
void AddQ(int item,Stack Ssmall,Stack Sbig) {
	if (!IsFull(Ssmall)) Push(Ssmall, item);
	else if (IsEmpty(Sbig)) {
		while (!IsEmpty(Ssmall)) {
			Push(Sbig, Pop(Ssmall));
		}
		Push(Ssmall, item);
	}
	else {
		printf("ERROR:Full\n");
	}
}
void DeleteQ(Stack Ssmall, Stack Sbig) {
	if (!IsEmpty(Sbig)) printf("%d\n", Pop(Sbig));
	else if (!IsEmpty(Ssmall)) {
		while (!IsEmpty(Ssmall)) {
			Push(Sbig, Pop(Ssmall));
		}
		printf("%d\n", Pop(Sbig));
	}
	else printf("ERROR:Empty\n");
}
int main()
{
	int big, small, t1, t2;
	scanf("%d %d", &t1, &t2);
	big = t1 > t2 ? t1 : t2;
	small = t1 > t2 ? t2 : t1;
	Stack Ssmall = (Stack)malloc(sizeof(struct stack));
	Stack Sbig = (Stack)malloc(sizeof(struct stack));
	Ssmall->MaxSize = small;
	Sbig->MaxSize = big;
	Ssmall->top = -1;
	Sbig->top = -1;
	Ssmall->data = (int *)malloc(Ssmall->MaxSize * sizeof(int));
	Sbig->data = (int *)malloc(Sbig->MaxSize * sizeof(int));
	char temp;
	int t;
	while (1) {
		temp = getchar();
		temp = getchar();
		if (temp == 'T') break;
		if (temp == 'A') {
			scanf("%d", &t);
			AddQ(t, Ssmall, Sbig);
		}
		else {
			DeleteQ(Ssmall, Sbig);
		}
	}
	return 0;
}

测试结果

基础实验3-2.5-堆栈模拟队列-函数题

问题整理

1.不要想当然地以为输入的数据是从1-n,经验证,也是有0的存在的。