面试题-剑指offer-两个队列实现栈
2018-01-29 23:38
344 查看
#include <iostream>
#include <queue>
using namespace std;
template <typename T>
class MyStack
{
public:
MyStack();
~MyStack();
void MyPush(const T& value);
T MyPop();
private:
queue<T> mq1;
queue<T> mq2;
};
template <typename T>
MyStack<T>::MyStack()
{
}
template <typename T>
MyStack<T>::~MyStack()
{
}
template <typename T>
void MyStack<T>::MyPush(const T& value)
{
mq1.push(value);
}
template <typename T>
T MyStack<T>::MyPop()
{
while(mq1.size()>1)
{
T& tmp = mq1.front();
mq2.push(tmp);
mq1.pop();
}
// 当 队列 mq1 中没有元素时,并且 mq2 中的元素个数 大于 1 时,将 mq2 中的元素压入 mq1 中
// 将 mq2 中的队头 出队
if (mq1.size() == 0 && mq2.size() >= 1)//当队1为空 队2元素大于1
{
while (mq2.size() > 1)
{
T& tmp = mq2.front();//队2头进队1 留队尾元素
mq2.pop();
mq1.push(tmp);
}
T tmp = mq2.front();
mq2.pop();
return tmp;
}
if (mq1.size() == 0 && mq2.size() == 0)//两个队列为空 判断都出队了
throw "stack is empty";
if (mq1.size() == 1)//当队1还有一个元素 出队
{
T tmp = mq1.front();
mq1.pop();
return tmp;
}
}
int main()
{
MyStack<char> s;
s.MyPush('A');
s.MyPush('B');
s.MyPush('C');
s.MyPush('D');
try
{
cout << "pop : " << s.MyPop() << endl;
cout << "pop : " << s.MyPop() << endl;
cout << "pop : " << s.MyPop() << endl;
s.MyPush('E');
cout << "pop : " << s.MyPop() << endl;
cout << "pop : " << s.MyPop() << endl;
cout << "pop : " << s.MyPop() << endl;
}
catch (const char *ptr)
{
printf("%s\n", ptr);
}
return 0;
}
相关文章推荐
- 【剑指offer】面试题7:两个栈实现队列
- 【剑指Offer面试题】 九度OJ1512:用两个栈实现队列
- 剑指Offer——面试题7:用两个栈实现队列
- 剑指Offer面试题9:用两个栈实现队列
- [剑指offer]面试题7:用两个栈实现队列
- 剑指Offer:面试题7 用两个栈实现队列
- 剑指offer--面试题7:用两个栈实现队列--Java实现
- 剑指offer-->面试题7 用两个栈实现队列
- 剑指offer面试题java实现之题7:用两个栈模拟一个队列的入队和出队操作
- 【剑指offer】面试题:两个队列实现栈
- 剑指Offer面试题7用两个栈实现队列(附带用两个队列实现栈)
- 剑指offer - 面试题7:用两个栈实现队列
- 【剑指offer】面试题7:用两个栈实现队列
- 剑指offer面试题[7]-用两个栈实现队列
- 剑指offer-面试题07-用两个栈实现队列
- [剑指offer][面试题07-扩展]用两个队列实现栈
- 剑指offer---面试题7 用两个栈实现队列
- 剑指offer面试题7:用两个栈实现队列
- 剑指Offer面试题7:用两个栈实现队列 Java实现
- 剑指 offer 面试题 7 : 用两个栈来实现队列