天天看點

PTA練習題:堆棧模拟隊列

設已知有兩個堆棧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()。

輸入格式:

輸入首先給出兩個正整數N1和N2,表示堆棧S1和S2的最大容量。随後給出一系列的隊列操作: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

分析:

PTA練習題:堆棧模拟隊列
#include<stdio.h>
int main()
{
	int N1,N2;
	scanf("%d %d",&N1,&N2);
	int max,min;
	if(N1>N2)
	{
		max = N1;
		min = N2;
	}
	else
	{
		max = N2;
		min = N1;
	}
	int s1[min];
	int s2[max];
	int top1 = 0;
	int top2 = 0;
	char c;
	int item;
	scanf("%c",&c);
	while(c != 'T')
	{
		if(c == 'A')
		{
			scanf("%d",&item);
			if(top1 < min)
			{
				s1[top1++] = item;
			}
			else if(top2 == 0)
			{
				while(top1 != 0)
				{
					s2[top2++] = s1[--top1];
				}
				s1[top1++] = item;
			}
			else
			{
				printf("ERROR:Full\n");
			}
		}
		else if(c == 'D')
		{
			if(top2 != 0)
			{
				printf("%d\n",s2[--top2]);
			}
			else if(top2 == 0 && top1 != 0)
			{
				while(top1 != 0)
				{
					s2[top2++] = s1[--top1];
				}
				printf("%d\n",s2[--top2]);
			}
			else
			{
				printf("ERROR:Empty\n");
			}
		}
		scanf("%c",&c);
	}
	return 0;
}
           

繼續閱讀