232.用栈实现队列
- 用两个栈来实现
- 当pop时,检测out栈是否为空,若为空,则将in栈的元素全都放入out栈中
class MyQueue {
private Stack<Integer> in;
private Stack<Integer> out;
public MyQueue() {
in = new Stack<>();
out = new Stack<>();
}
public void push(int x) {
in.push(x);
}
public int pop() {
if (out.isEmpty()) {
while (!in.isEmpty()) {
out.push(in.pop());
}
}
return out.pop();
}
public int peek() {
if (out.isEmpty()) {
while (!in.isEmpty()) {
out.push(in.pop());
}
}
return out.peek();
}
public boolean empty() {
return in.isEmpty() && out.isEmpty();
}
}
225. 用队列实现栈
- 单个队列方法
- 将前面n-1个元素弹出并加入底部,这样就可以模拟后进先出
class MyStack {
private Queue<Integer> a;
public MyStack() {
a = new LinkedList<>();
}
public void push(int x) {
int n = a.size();
a.offer(x);
while (n > 0) {
a.offer(a.poll());
n--;
}
}
public int pop() {
return a.poll();
}
public int top() {
return a.peek();
}
public boolean empty() {
return a.isEmpty();
}
}