5-22 堆栈模拟队列 (25分)

5-22 堆栈模拟队列   (25分)

设已知有两个堆栈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

思路:
把容量小的栈来入队,把容量大的栈来出队。当容量小的栈满时就将元素全部转入容量大的栈中,
其中的操作都遵循栈的出栈和入栈。两个栈就模拟成了队列,遵循先入先出。

#include<stdio.h>
#include<algorithm>
#include<stdlib.h>
#include<string.h>

using namespace std;

struct SNode{
	int num;
	struct SNode * next;
};

typedef struct SNode * STACK;

STACK create()
{
	STACK shead = (STACK)malloc(sizeof(struct SNode));
	shead->next = NULL;
	return shead;
}

void push(STACK S,int number)
{
	STACK snew = (STACK)malloc(sizeof(struct SNode));
	snew->num = number;
	snew->next = S->next;
	S->next = snew;
}

int pop(STACK S)
{
	STACK p;
	int number;
	p = S->next;
	number = p->num;
	S->next = p->next;
	free(p);
	return number;
}

int main(void)
{
	STACK s1 = create();
	STACK s2 = create();
	int n1,n2;
	scanf("%d%d",&n2,&n1);
	int count1 = 0,count2 = 0;/*conut1代表容量小的栈中的个数,count2代表容量大的*/ 
	while(1)
	{
		char ch;
		int num;
		scanf("%c",&ch);
		if(ch == 'A')
		{
			scanf("%d",&num);
			getchar();
			if(count1 < n1)
			{
				push(s1,num);
				count1++;
			}
			else
			{
				printf("ERROR:Full\n");
			}
		}
		else if(ch == 'D')
		{
			if(count2 > 0)
			{
				printf("%d\n",pop(s2));
				count2--;
			}
			else
			{
				printf("ERROR:Empty\n");
			}
		}
		else if(ch =='T')
		{
			break;
		}
		
		if(count1 == n1 && count2 == 0)/*只要s1栈满,而s2空,就把s1全部转入s2*/ 
		{
			while(count1 != 0)
			{
				push(s2,pop(s1));
				count1--;
				count2++;
			}
		}
	}	
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值