如何用栈实现队列Java 栈和队列的功能
原创

如何用栈实现队列Java 栈和队列的功能

好文

文章目录[隐藏]

题目

请你仅使用两个栈实现先入先出队列。队列应当支持一般队列的支持的所有操作(push、pop、peek、empty):

实现 MyQueue 类:

void push(int x) 将元素 x 推到队列的末尾

int pop() 从队列的开头移除并返回元素

int peek() 返回队列开头的元素

boolean empty() 如果队列为空。返回 true ;否则。返回 false

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/implement-queue-using-stacks

著作权归领扣网络所有。商业转载请联系官方授权。非商业转载请注明出处。

代码

/***https://leetcode-cn.com/problems/implement-queue-using-stacks/*/classMyQueue{Deque<Integer>inStack;Deque<Integer>outStack;/**Initializeyourdatastructurehere.*/publicMyQueue(){inStack=newLinkedList<>();outStack=newLinkedList<>();}/**Pushelementxtothebackofqueue.*/publicvoidpush(intx){inStack.push(x);}/**Removestheelementfrominfrontofqueueandreturnsthatelement.*/publicintpop(){if(outStack.isEmpty()){inStack2outStack();}returnoutStack.pop();}/**Getthefrontelement.*/publicintpeek(){if(outStack.isEmpty()){inStack2outStack();}returnoutStack.peek();}/**Returnswhetherthequeueisempty.*/publicbooleanempty(){returninStack.isEmpty()&&outStack.isEmpty();}privatevoidinStack2outStack(){while(!inStack.isEmpty()){outStack.push(inStack.pop());}}}

总结

* 这是一个非常常见的题目。栈的特性是先入后出。队列的特性是先入先出。因此。我们可以用两个栈来实现队列。inStack记录输入。outStack记录输出。以上代码巧妙的地方是在outStack为空的时候。将inStack的数据输入进去。

您还感兴趣的文章推荐

以上就是由互联网推广工程师 桔子生活网 整理编辑的,如果觉得有帮助欢迎收藏转发~

分享到 :
相关推荐

回复 独一人 取消回复

登录... 后才能评论

评论(2)

  • 独一人 永久VIP 2022年12月14日 02:33:23

    如何用栈实现队列Java 栈和队列的功能 这篇解答确实也是太好了

  • 少女恶习 永久VIP 2022年12月14日 02:33:23

    队列,元素,先入,为空,开头,题目,特性,两个,代码,是在

  • 对不起是种借口 永久VIP 2022年12月14日 02:33:23

    题目请你仅使用两个栈实现先入先出队列。队列应当支持一般队列的支持的所有操作(push、pop、peek、empty):实