思想: 这里需要2个栈来实现,把元素全部放到第一个栈中,再将第一个栈的元素放到第二个栈中,此时栈顶的元素就是我们要出队列的元素,依次下去可以完成操作;
importjava.util.Stack; /*** Created with IntelliJ IDEA.* Description:* User: Snk* Date: 2023-02-07* Time: 12:50*/classMyQueue { privateStack<Integer>stack1; privateStack<Integer>stack2; publicMyQueue() { this.stack1=newStack<>(); this.stack2=newStack<>(); } publicvoidpush(intx) { stack1.push(x); } publicintpop() { if(empty()){ return-1; } if (stack2.isEmpty()) { while (!stack1.isEmpty()) { stack2.push(stack1.pop()); } } returnstack2.pop(); } publicintpeek() { if(empty()){ return-1; } if (stack2.isEmpty()) { while (!stack1.isEmpty()) { stack2.push(stack1.pop()); } } returnstack2.peek(); } publicbooleanempty() { returnstack1.isEmpty() &&stack2.isEmpty(); } }