两个队列模拟栈

本文详细介绍了如何利用两个队列来模拟栈的功能,通过实例代码展示了如何进行压栈、弹栈等操作,揭示了队列与栈在数据结构转换中的巧妙应用。
摘要由CSDN通过智能技术生成

 

 

#pragma once
#include<queue>
#include<stack>
using namespace std;
template<typename T>
class CStack
{
public:
	CStack(void);
	~CStack(void);
	void push(const T& num);
	T pop();
	T top();
	void swapQueue();// 交换dataQueue和helpQueue
private:
	queue<T>dataQueue;
	queue<T>helpQueue;
};

template<typename T>
inline CStack<T>::CStack(void)
{
}

template<typename T>
inline CStack<T>::~CStack(void)
{
}

template<typename T>
inline void CStack<T>::push(const T& num)
{
	dataQueue.push(num);
}

template<typename T>
inline T CStack<T>::pop()
{
	if (dataQueue.empty()) {
		throw std::runtime_error("queue is empty");
	}
	else {
		while (dataQueue.size() > 1) {  // 当dataQueue
			helpQueue.push(dataQueue.front());
			dataQueue.pop();
		}
		T res = dataQueue.front();    // 这个dataQueue的最后元素也就是stack的栈顶元素
		dataQueue.pop();    // dataQueue已经为空,helpQueue存放n-1个数
		swapQueue();   // 交换二个队列
		return res;
	}
}



template<typename T>
inline T CStack<T>::top()
{
	if (dataQueue.empty()) {
		throw std::runtime_error("queue is empty");
	}
	else {
		while (dataQueue.size() > 1) {  // 当dataQueue
			T data = dataQueue.front();
			dataQueue.pop();
			helpQueue.push(data);
		}
		T res = dataQueue.front();    // 这个dataQueue的最后元素也就是stack的栈顶元素
		dataQueue.pop();    // 此时dataQueue已经为空,helpQueue存放n-1个数
		helpQueue.push(res);    // 获取top元素需要将原来数据返回
		swapQueue();
		return res;
	}
	
}

template<typename T>
inline void CStack<T>::swapQueue()
{
	std::queue<T> tmp = dataQueue;
	dataQueue = helpQueue;
	helpQueue = tmp;
}

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值