目录
剑指Offer-面试题8---用两个栈实现队列
这道题比较简单、随便写写。
1、题目
用两个栈来实现一个队列,完成队列的Push和Pop操作。
template<typename T>
class CQueue
{
private:
stack<T> stack1;
stack<T> stack2;
public:
//入队列、出队列
void Push(const T& node);
T Pop();
};
template<typename T>
void CQueue<T>::Push(const T& node)
{
stack1.push(node);
}
template<typename T>
T CQueue<T>::Pop()
{
//出队列时,把pop栈1元素,push到栈2中。反转过来。
//这样pop栈2中的元素,就相当于实现了出队列。
if(stack2.empty())
{
if(stack1.empty())
{
//为空时,扔出报错信息
throw ("队列为空,无法出队列!");
}
while(!stack1.empty())
{
T temp = stack1.top();
stack1.pop();
stack2.push(temp);
}
}
T del = stack2.top();
stack2.pop();
return del;
}
int main()
{
CQueue<int> que;
que.Push(1);
que.Push(2);
que.Push(3);
try{
//先出队列再输出,不然cout输出无法识别要输出的类型
int del = que.Pop();
cout<<del;
}
catch(const char* msg){
//捕获错误信息并输出
cerr<<msg<<endl;
}
return 0;
}