Leetcode---剑指Offer题9---用两个栈实现队列
目录
剑指Offer-面试题8---用两个栈实现队列
1、题目
https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof/
用两个栈来实现一个队列,完成队列的Push和Pop操作。
C#
public class CQueue
{
private Stack<int> upStack;
private Stack<int> downStack;
public CQueue()
{
upStack = new Stack<int>();
downStack = new Stack<int>();
}
public void AppendTail(int value)
{
upStack.Push(value);
}
public int DeleteHead()
{
if (upStack.Count==0 && downStack.Count == 0)
return -1;
if (downStack.Count==0)
{
while (upStack.Count != 0)
{
downStack.Push(upStack.Pop());
}
}
return downStack.Pop();
}
}
C++
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;
}