探索栈与队列的关系(以《用两个栈组成队列》为例)

题目

编写一个类,用两个栈实现队列,支持队列(先进先出)的基本操作:

push:将一个元素置入queue中

​ pop:

  • 移除queue中的第一元素

  • 此函数无返回值,想处理被移除的元素,必须先调用front()

  • 调用者保证queue非空

front:

  • 返回第一个被置入的元素,即返回queue最前端的元素

  • 调用者保证queue不空

back:

  • 返回最后一个被插入的元素

  • 调用者保证queue非空

代码

// A queue consisting of two stacks.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
#include<stack>
#include<queue>
using namespace std;
class MyTwoStackToQueue
{
public:
	void push(int newnum);
	void pop();
	int front();
	int back();
	int backnum;

private:
	stack<int>pushstack;
	stack<int>popstack;
	void adjust();

};
void MyTwoStackToQueue::adjust()//这个函数时有必要的,它能把第一个栈中所有数集体压缩进第二个栈上
{
	while (!pushstack.empty())
	{
		popstack.push(pushstack.top());
		pushstack.pop();
	}
}

void MyTwoStackToQueue::push(int newnum)//这个函数中我们可以不用想数怎么从一个栈再到另一个栈,直接先把所有的数先压入一个栈中,后面再集体压入下一个栈上
{
		backnum = newnum;
		pushstack.push(newnum);
		
}
void MyTwoStackToQueue::pop()
{
	if (popstack.empty())
		adjust();
	if (popstack.empty())
	{
		cout << "The queue is empty! Can't pop!" << endl;
		return;
	}
	popstack.pop();
}

int MyTwoStackToQueue::front()
{
	if (popstack.empty())
	{
		adjust();
	}
	return popstack.top();
}
int MyTwoStackToQueue::back()
{
	return backnum;
}

int _tmain(int argc, _TCHAR* argv[])
{
	int i, j;
	int aa = 93;
	MyTwoStackToQueue queue1;
	for (i = 0; i < 10; i++)
	{
		queue1.push(i);
	}
	cout << "front:" << queue1.front() << "," << "back:" << queue1.back() << endl;
	queue1.pop();
	cout << "pop!" << endl;
	cout << "front:" << queue1.front() << "," << "back:" << queue1.back() << endl;
	queue1.push(10);
	cout << "push10!" << endl;
	cout << "front:" << queue1.front() << "," << "back:" << queue1.back() << endl;
	for (j = 0; j < 9; j++)
	{
		queue1.pop();
	}
	cout << "pop*8" << endl;
	cout << "front:" << queue1.front() << "," << "back:" << queue1.back() << endl;
	cout << endl;
	
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值