【leetcode】【225】Implement Stack using Queues
来源:互联网 发布:网络用语贼g2什么意思 编辑:程序博客网 时间:2024/05/23 00:09
一、问题描述
Implement the following operations of a stack using queues.
- push(x) -- Push element x onto stack.
- pop() -- Removes the element on top of the stack.
- top() -- Get the top element.
- empty() -- Return whether the stack is empty.
- You must use only standard operations of a queue -- which means only
push to back
,peek/pop from front
,size
, andis empty
operations are valid. - Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
- You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).
二、问题分析
用Queues来实现stack,显然一个queue是完不成,因此可以采用两个queues。具体的操作可以看代码,并不难,无非就是两个队列相互的一些offer或者poll操作来完成stack的pop和push的功能。可以自己手动画一下。
三、Java AC代码
class MyStack { private LinkedList<Integer> queue1 = new LinkedList<Integer>();private LinkedList<Integer> queue2 = new LinkedList<Integer>(); // Push element x onto stack. public void push(int x) { if (queue1.isEmpty()) {queue1.offer(x);while(!queue2.isEmpty()){queue1.offer(queue2.poll());}}else {queue2.offer(x);while(!queue1.isEmpty()){queue2.offer(queue1.poll());}} } // Removes the element on top of the stack. public void pop() { if (!queue1.isEmpty()) {queue1.poll();}else if (!queue2.isEmpty()){queue2.poll();} } // Get the top element. public int top() { if (!queue1.isEmpty()) {return queue1.peek();}else {return queue2.peek();} } // Return whether the stack is empty. public boolean empty() { return queue1.isEmpty()&&queue2.isEmpty(); }}
0 0
- Implement Stack using Queues - LeetCode 225
- LeetCode 225: Implement Stack using Queues
- Leetcode[225]-Implement Stack using Queues
- leetcode 225: Implement Stack using Queues
- leetcode 225 Implement Stack using Queues
- leetcode 225:Implement Stack using Queues
- [Leetcode 225, Easy] Implement Stack using Queues
- LeetCode---(225)Implement Stack using Queues
- leetcode-225-Implement Stack using Queues
- leetCode #225 Implement Stack using Queues
- [leetcode-225]Implement Stack using Queues(c++)
- [LeetCode 225] Implement Stack using Queues
- Leetcode #225 Implement Stack using Queues
- [leetcode 225] Implement Stack using Queues
- Leetcode NO.225 Implement Stack using Queues
- LeetCode(225) Implement Stack using Queues
- LeetCode 225 Implement Stack using Queues
- 【LEETCODE】225-Implement Stack using Queues
- Java——SAX解析XML文件
- Plugin is too old,.....Android studio提示问题
- 9.打开ZF的错误提示
- 13. Roman to Integer
- android的 Intent跳转失败,显示“很抱歉,**已停止运行”,这是为什么?
- 【leetcode】【225】Implement Stack using Queues
- PHP 函数作为参数 及其序列化
- org.hibernate.engine.jndi.JndiException: Error parsing JNDI name
- Hadoop伪分布式环境搭建错误及解决
- 我用HttpClient-MultipartEntity上传文字和图像 服务端没响应。
- springmvc中对静态资源的处理
- 冒泡排序、选择排序、插入排序
- JDK安装和配置环境
- Android与服务器端数据交互(基于SOAP协议整合android+webservice)