手写代码:两个栈实现一个队列
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);
}
public int pop() {
if(stack2.isEmpty()){
while(!stack1.isEmpty()){
int node=stack1.pop();
stack2.push(node);
}
}
return stack2.pop();
}
} template<class T>
class Queue
{
public:
void Push(const T& node) // 模拟进队
{
stack1.push(node);
}
void Pop() // 模拟出队
{
if (stack1.empty() && stack2.empty()) // 说明此时队列为空
{
cout << "此时队列为空" << endl;
}
if(!stack2.empty()) // stack2 不为空,stack2出队列
{
stack2.pop();
}
else // stack2 为空,stack1中元素入栈到stack2
{
while (stack1.size() > 0)
{
stack2.push(stack1.top());
stack1.pop();
}
stack2.pop(); //stack2进栈完成,模拟出队
}
}
int GetFront() // 对头就是栈顶,用前判断队列是否为空
{
if (stack2.empty())
{
while (stack1.size() > 0)
{
stack2.push(stack1.top());
stack1.pop();
}
}
return stack2.top();
}
private:
stack<T> stack1;
stack<T> stack2;
};