题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
参考代码
class Solution
{
public:
void push(int node)
{
stack1.push(node);
}
int pop()
{
if(stack2.empty())
{
while(!stack1.empty())
{
stack2.push(stack1.top());
stack1.pop();
}
}
if(!stack2.empty())
{
int res = stack2.top();
stack2.pop();
return res;
}
}
private:
stack<int> stack1;
stack<int> stack2;
};
拓展解法
还有个问题是“两个队列实现一个栈”,思路也不难,这里不再详述,参考代码如下:
template<typename T> class CStack
{
public:
CStack(void);
~CStack(void);
void appendTail(const T& node);
T deleteHead();
private:
queue<T> q1;
queue<T> q2;
};
template<typename T>
void CStack<T>::appendTail(const T& node)//实现栈元素的插入
{
//数据的插入原则:保持一个队列为空,一个队列不为空,往不为空的队列中插入元素
if (!q1.empty())
{
q1.push(node);
}
else
{
q2.push(node);
}
}
template<typename T>
T CStack<T>::deleteHead()//实现栈元素的删除
{
int ret = 0;
if (!q1.empty())
{
int num = q1.size();
while (num > 1)
{
q2.push(q1.front());
q1.pop();
--num;
}
ret = q1.front();
q1.pop();
}
else
{
int num = q2.size();
while (num > 1)
{
q1.push(q2.front());
q2.pop();
--num;
}
ret = q2.front();
q2.pop();
}
return ret;
}