面试题9:用两个栈实现队列

这篇博客探讨了如何利用两个栈来实现队列的功能,以及如何使用两个队列来模拟栈的操作。示例代码分别展示了这两种实现方式,通过pushData和popData方法完成数据的入队和出队、入栈和出栈操作。这些实现方法揭示了数据结构之间的转换和复用原理。
摘要由CSDN通过智能技术生成

题目:用两个栈实现队列功能

#include <iostream>
#include <stack>

using namespace std;

template<class T>
class MyQueue {
private:
	stack<T> s1;
	stack<T> s2;

public:
	MyQueue(){}
	~MyQueue(){}
	void pushData(T val)
	{
		s1.push(val);
	}
	bool queueEmpty()
	{
		if (s1.empty() && s2.empty())
			return true;
		else
			return false;
	}
	T popData()
	{
		T ret;
		if (queueEmpty())
			return -1;
		if (s2.empty())
		{
			while (!s1.empty())
			{
				s2.push(s1.top());
				s1.pop();
			}
		}
		ret = s2.top();
		s2.pop();
		return ret;
	}
};


int main()
{
	MyQueue<int> q;
	for(int i = 0; i < 10; ++i)
		q.pushData(i);
	while (!q.queueEmpty())
		cout << q.popData() << endl;
}

题目:用两个队列实现一个栈

#include <iostream>
#include <queue>

using namespace std;

template<class T>
class MyStack
{
private:
	queue<T> q1;
	queue<T> q2;

public:
	MyStack(){}
	~MyStack(){}
	bool isEmpty()
	{
		if (q1.empty() && q2.empty())
			return true;
		else
			return false;
	}
	void pushData(T val)
	{
		if (!q1.empty())
			q1.push(val);
		else
			q2.push(val);
	}
	T popData()
	{
		T ret;
		if (!q1.empty())
		{
			while (q1.size() > 1)
			{
				q2.push(q1.front());
				q1.pop();
			}
			ret = q1.front();
			q1.pop();
		}
		else
		{
			while (q2.size() > 1)
			{
				q1.push(q2.front());
				q2.pop();
			}
			ret = q2.front();
			q2.pop();
		}
		return ret;
	}
};

int main()
{
	MyStack<int> s;
	for (int i = 0; i < 10; ++i)
	{
		s.pushData(i);
	}
	while (!s.isEmpty())
		cout << s.popData() << endl;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值