232. 用栈实现队列
class MyQueue {
private Stack<Integer> input;
private Stack<Integer> output;
public MyQueue() {
input = new Stack<>();
output = new Stack<>();
}
public void push(int x) {
input.push(x);
}
public int pop() {
if(output.isEmpty()){
while(!input.isEmpty()){
output.push(input.pop());
}
}
return output.pop();
}
public int peek() {
if(output.isEmpty()){
while(!input.isEmpty()){
output.push(input.pop());
}
}
return output.peek();
}
public boolean empty() {
return input.isEmpty()&& output.isEmpty();
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/
225. 用队列实现栈
class MyStack {
private Queue<Integer> q1; // 主队列 用来存储栈的元素
private Queue<Integer> q2; // 辅助队列 用来在添加元素时进行调整
public MyStack() {
q1 = new LinkedList<>(); // 初始化主队列
q2 = new LinkedList<>(); // 初始化辅助队列
}
public void push(int x) {
q2.offer(x); // 将新元素添加到辅助队列的末尾
while(!q1.isEmpty()) {
q2.offer(q1.poll());
}
Queue<Integer> temp = q1;
q1 = q2;
q2 = temp;
}
public int pop() {
return q1.poll(); // 从主队列 栈顶 移除元素并返回
}
public int top() {
return q1.peek(); // 获取主队列 栈顶 的元素但不移除
}
public boolean empty() {
return q1.isEmpty(); //检查主队列是否非空
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/