这个是 Leetcode 232 题,用两个栈来实现一个先进先出的队列,实现了一个版本。
https://leetcode-cn.com/problems/implement-queue-using-stacks/
class MyQueue {
Stack<Integer> stack1 = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
/**
* Initialize your data structure here.
*/
public MyQueue() {
}
/**
* Push element x to the back of queue.
*/
public void push(int x) {
stack1.push(x);
}
/**
* Removes the element from in front of queue and returns that element.
*/
public int pop() {
while (!stack1.empty()) {
stack2.push(stack1.pop());
}
int result = stack2.pop();
while (!stack2.empty()) {
stack1.push(stack2.pop());
}
return result;
}
/**
* Get the front element.
*/
public int peek() {
while (!stack1.empty()) {
stack2.push(stack1.pop());
}
int result = stack2.peek();
while (!stack2.empty()) {
stack1.push(stack2.pop());
}
return result;
}
/**
* Returns whether the queue is empty.
*/
public boolean empty() {
return stack1.empty();
}
}