欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 创投人物 > LeetCode[232]用栈实现队列

LeetCode[232]用栈实现队列

2025/4/24 20:58:52 来源:https://blog.csdn.net/m0_57209427/article/details/147364743  浏览:    关键词:LeetCode[232]用栈实现队列

思路:

一道很简单的题,就是栈是先进后出,队列是先进先出,用两个栈底相互对着,这样一个队列就产生了,右栈为空的情况,左栈栈底就是队首元素,所以我们需要将左栈全部压入右栈,右栈不为空,那么右栈就是之前压入过,这时右栈栈顶元素就是队首元素,大家画画图应该就明白了

class MyQueue {Stack<Integer> left;Stack<Integer> right;public MyQueue() {left = new Stack<>();right = new Stack<>();}public void push(int x) {left.push(x);}public int pop() {if (right.isEmpty()) {while (!left.isEmpty()) {right.push(left.pop());}}return right.pop();}public int peek() {if (right.isEmpty()) {while (!left.isEmpty()) {right.push(left.pop());}}return right.peek();}public boolean empty() {return left.isEmpty() && right.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();*/

 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词