栈实现队列
leetcode.cn/problems/im…
class MyQueue {
Stack<Integer> in;
Stack<Integer> out;
public MyQueue() {
in = new Stack<>();
out = new Stack<>();
}
public void in2Out() {
if (out.empty()) {
while (!in.empty()) {
out.push(in.pop());
}
}
}
public void push(int x) {
in.push(x);
in2Out();
}
public int pop() {
in2Out();
return out.pop();
}
public int peek() {
in2Out();
return out.peek();
}
public boolean empty() {
return in.empty() && out.empty();
}
}
队列实现栈
leetcode.cn/problems/im…
class MyStack {
Queue<Integer> queue;
public MyStack() {
queue = new LinkedList<>();
}
public void push(int x) {
int n = queue.size();
queue.offer(x);
while(n>0){
queue.offer(queue.poll());
n--;
}
}
public int pop() {
return queue.poll();
}
public int top() {
return queue.peek();
}
public boolean empty() {
return queue.isEmpty();
}
}