careercup3.5用两个栈实现一个队列

3.5 Implement a MyQueue class which implements a queue using two stacks.

分析

Queue:first in first out

stack:first in last out
由于队列移除元素移除的是队尾元素,因此用栈s2保持队尾元素。
两个栈
栈s1中:最新的元素在最上面
栈s2中:最旧的元素在最上面
添加元素在栈s1中操作。移除元素时,若栈s2中有元素,则弹出栈顶元素即可。否则把s1中的元素弹出依次压到栈s2中,这样保持最早被压入的元素在s2的栈顶。


#include<iostream>
#include<stack>
using namespace std;

template<typename T>
class MyQueue{
public:
	MyQueue();
	void add(T elem);
	T top();
	int size();
	T remove();
private:
	stack<T> s1;
	stack<T> s2;

};
template<typename T>
MyQueue<T>::MyQueue(){}
template<typename T>
int MyQueue<T>::size(){
	return s1.size()+s2.size();
}
template<typename T>
void MyQueue<T>::add(T elem){
	s1.push(elem);
}
template<typename T>
T MyQueue<T>::top(){
	if(!s2.empty())
		return s2.top();
	while(!s1.empty()){
		s2.push(s1.top());
		s1.pop();
	}
	return s2.top();

}
template<typename T>
T MyQueue<T>::remove(){
	T elem;
	if(!s2.empty()){
		elem=s2.top();
		s2.pop();
		return elem;
	}
	while(!s1.empty()){
		s2.push(s1.top());
		s1.pop();
	}
	elem=s2.top();
	s2.pop();
	return elem;
}



int main(){

	MyQueue<int> a;
	a.add(5);
	a.add(6);
	a.add(7);
	a.add(8);
	a.add(9);
	a.remove();
	cout<<a.top()<<endl;
	cout<<a.size()<<endl;
	//for test
	system("pause");
	return 0;





}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值