本文主要是介绍2020-12-11(232. 用栈实现队列),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
class MyQueue {Stack<Integer> a=new Stack<>(); //存放Stack<Integer> b=new Stack<>(); //输出int front;/** Initialize your data structure here. */public MyQueue() {}/** Push element x to the back of queue. */public void push(int x) {if(a.isEmpty()){front=x;}a.push(x);}/** Removes the element from in front of queue and returns that element. */public int pop() {if(b.isEmpty()){while(!a.isEmpty()){b.push(a.pop());}}return b.pop();}/** Get the front element. */public int peek() {if(!b.isEmpty()){return b.peek();}return front;}/** Returns whether the queue is empty. */public boolean empty() {return a.isEmpty()&&b.isEmpty();}
}/*** Your MyQueue object will be instantiated and called as such:* MyQueue obj = new MyQueue();* obj.push(x);* int param_2 = obj.pop();* int param_3 = obj.peek();* boolean param_4 = obj.empty();*/
官方真香,当时一想到元素分散到两个栈,就不知道怎么处理。看答案就是别怕,分就分呗,能完成功能就行,管他的实际结构是啥呢。每个pop操作时,当b为空时就把a全部搬过来。这个是关键。
这篇关于2020-12-11(232. 用栈实现队列)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!