1. 用栈实现队列
力扣题目链接
public class MyQueue {
Stack<Integer> in;
Stack<Integer> out;
public MyQueue() {
in = new Stack<>();
out = new Stack<>();
}
public void push(int x) {
in.push(x);
}
public int pop() {
dumpstackIn();
return out.pop();
}
public int peek(){
dumpstackIn();
return out.peek();
}
public boolean empty(){
dumpstackIn();
return out.isEmpty();
}
private void dumpstackIn(){
if (out.isEmpty()) {
while (!in.isEmpty()) {
out.push(in.pop());
}
}
}
}
2. 用队列实现栈
力扣题目链接
public class MyStack {
Queue<Integer> queue;
public MyStack() {
queue = new LinkedList<>();
}
public void push(int x) {
queue.offer(x);
theLastElementToTheFront();
}
public int pop() {
return queue.poll();
}
public int top() {
return queue.peek();
}
public boolean empty() {
return queue.isEmpty();
}
public void theLastElementToTheFront() {
for (int i = 0; i < queue.size() - 1; i++) {
queue.offer(queue.poll());
}
}
}