牛客网&剑指Offer&用两个栈实现队列![在这里插入图片描述](https://img-blog.csdnimg.cn/201905282035133.png)
代码实现
class Solution
{
public:
void push(int node) {
stack1.push(node);
}
int pop() {
int revalue = 0;
if(stack2.empty() == true)
{
while(stack1.empty() == false)
{
stack2.push(stack1.top());
stack1.pop();
}
}
revalue = stack2.top();
stack2.pop();
return revalue;
}
private:
stack<int> stack1;
stack<int> stack2;
};
int main()
{
Solution test;
int value = 0;
for (int i = 0; i < 5; i++)
{
test.push(i);
}
for (int i = 0; i < 5; i++)
{
value = test.pop();
std::cout << value << " ";
}
}
编程笔记
- 代码实现解题思路:1.入队:将元素进栈A;2.出队:判断栈B是否为空,如果为空,则将栈A中所有元素pop,并push进栈B,栈B出栈;3.如果不为空,栈B直接出栈。
- 用两个队列实现一个栈的功能 ? 要求给出算法和思路:1.入栈:将元素进队列A;2.出栈:判断队列A中元素的个数是否为1,如果等于1,则出队列,否则将队列A中的元素 以此出队列并放入队列B,直到队列A中的元素留下一个,然后队列A出队列,再把队列B中的元素出队列以此放入队列A中。
- 熟悉队列的基本操作;
- 熟悉栈的基本操作;