华拓科技网
您的当前位置:首页PTA:7-1 堆栈模拟队列

PTA:7-1 堆栈模拟队列

来源:华拓科技网

p.s.自用

题目

设已知有两个堆栈S1和S2,请用这两个堆栈模拟出一个队列Q。

所谓用堆栈模拟队列,实际上就是通过调用堆栈的下列操作函数:

  • int IsFull(Stack S):判断堆栈S是否已满,返回1或0;
  • int IsEmpty (Stack S ):判断堆栈S是否为空,返回1或0;
  • void Push(Stack S, ElementType item ):将元素item压入堆栈S
  • ElementType Pop(Stack S ):删除并返回S的栈顶元素。

实现队列的操作,即入队void AddQ(ElementType item)和出队ElementType DeleteQ()

输入格式

输入首先给出两个正整数N1N2,表示堆栈S1S2的最大容量。随后给出一系列的队列操作:A item表示将item入列(这里假设item为整型数字);D表示出队操作;T表示输入结束。

输出格式

对输入中的每个D操作,输出相应出队的数字,或者错误信息ERROR:Empty。如果入队操作无法执行,也需要输出ERROR:Full。每个输出占1行。

输入样例

3 2
A 1 A 2 A 3 A 4 A 5 D A 6 D A 7 D A 8 D D D D T

输出样例

ERROR:Full
1
ERROR:Full
2
3
4
7
8
ERROR:Empty

代码长度

16 KB

时间

400 ms

内存

MB

8192 KB

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#define ElementType int

typedef struct sstack
{
	ElementType* data;
	int top;
	int maxNum;
}mystack, * Stack;
//初始化
Stack init(int n)
{
	Stack s = (Stack)malloc(sizeof(mystack));
	s->data = (int*)malloc(n * sizeof(int));
	s->top = -1;
	s->maxNum = n;
	return s;
}

int IsFull(Stack S) // 判断堆栈S是否已满,返回1或0
{
	if (S->top == S->maxNum - 1) // 满
		return 1;
	return 0;
}
int IsEmpty(Stack S) // 判断堆栈S是否为空,返回1或0
{
	if (S->top == -1) // 空
		return 1;
	return 0;
}
void Push(Stack S, ElementType item) // 将元素item压入堆栈S
{
	S->data[++S->top] = item;
}
ElementType Pop(Stack S) // 删除并返回S的栈顶元素
{
	return S->data[S->top--];
}

int main()
{
	int n1, n2; // 堆栈S1和S2的最大容量
	scanf("%d%d", &n1, &n2);
	if (n1 > n2) // 小容量的做入栈
	{
		int t = n1;
		n1 = n2;
		n2 = t;
	}
	Stack s1 = init(n1); // 入队操作
	Stack s2 = init(n2); // 出队操作
	char operation; // 操作
	ElementType item; // 数字
	while (1)
	{
		getchar();
		scanf("%c", &operation);
		if (operation == 'A') // 入队
		{
			scanf("%d", &item);
			if (!IsFull(s1)) // s1未满
				Push(s1, item);
			else if (IsFull(s1) && IsEmpty(s2)) // s2空
			{
				while (!IsEmpty(s1)) // s1非空s2非满
					Push(s2, Pop(s1));
				Push(s1, item);
			}
			else if (IsFull(s1) && !IsEmpty(s2))
				printf("ERROR:Full\n");
		}
		else if (operation == 'D') // 出队
		{
			if (IsEmpty(s1) && IsEmpty(s2)) // s1s2都空
				printf("ERROR:Empty\n");
			else if (!IsEmpty(s2)) // s2非空
				printf("%d\n", Pop(s2));
			else if (!IsEmpty(s1) && IsEmpty(s2)) // s1非空s2空
			{
				while (!IsEmpty(s1)) // s1非空s2非满
					Push(s2, Pop(s1));
				printf("%d\n", Pop(s2));
			}
		}
		else if (operation == 'T') // 结束
			break;
	}
	return 0;
}

因篇幅问题不能全部显示,请点此查看更多更全内容