package com.company;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Stack;
public class MyQueue {
private Stack<Integer> stackIn;
private Stack<Integer> stackOut;
public MyQueue() {
stackIn = new Stack<>();
stackOut = new Stack<>();
}
public void push(int x) {
stackIn.push(x);//这里必须是装到stackIn里面,因为后续dumpstackIn倒入元素是从stackIn倒入到stackOut
}
//弹出顶端值
public int pop() {
dumpstackIn();
return stackOut.pop();
}
//获取顶端值,不弹出
public int peek() {
dumpstackIn();
return stackOut.peek();
}
public boolean empty() {
return stackIn.isEmpty() && stackOut.isEmpty();
}
private void dumpstackIn() {//如果stackOut为空,那么将stackIn中的元素全部放到stackOut中
if (!stackOut.isEmpty()) {
return;
}
while (!stackIn.isEmpty()) {
stackOut.push(stackIn.pop());//弹出stackIn中的元素放到stackOut里
}
}
}
package com.company;
import java.util.*;
public class Main {
public static void main(String[] args) {
MyQueue queue=new MyQueue();
queue.push(1);
queue.push(2);
queue.push(3);
System.out.println(queue.pop());
System.out.println(queue.pop());
System.out.println(queue.peek());
}
}