Java [Leetcode 232]Implement Queue using Stacks
2016-01-05 14:22
453 查看
题目描述:
Implement the following operations of a queue using stacks.
push(x) -- Push element x to the back of queue.
pop() -- Removes the element from in front of queue.
peek() -- Get the front element.
empty() -- Return whether the queue is empty.
Notes:
You must use only standard operations of a stack -- which means only
Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
解题思路:
使用两个stack,一个用于插入数据,另一个用于输出数据。
代码如下:
Implement the following operations of a queue using stacks.
push(x) -- Push element x to the back of queue.
pop() -- Removes the element from in front of queue.
peek() -- Get the front element.
empty() -- Return whether the queue is empty.
Notes:
You must use only standard operations of a stack -- which means only
push to top,
peek/pop from top,
size, and
is emptyoperations are valid.
Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
解题思路:
使用两个stack,一个用于插入数据,另一个用于输出数据。
代码如下:
class MyQueue { Stack<Integer> input = new Stack<Integer>(); Stack<Integer> output = new Stack<Integer>(); // Push element x to the back of queue. public void push(int x) { input.push(x); } // Removes the element from in front of queue. public void pop() { peek(); output.pop(); } // Get the front element. public int peek() { if(output.empty()){ while(!input.empty()){ output.push(input.pop()); } } return output.peek(); } // Return whether the queue is empty. public boolean empty() { return input.empty() && output.empty(); } }
相关文章推荐
- Java [Leetcode 232]Implement Queue using Stacks
- LinkedBlockingQueue的put,add跟offer的区别(转)
- Arduino PWM的探究
- UML建模之时序图(Sequence Diagram)
- Leetcode215: Distinct Subsequences
- HDU 4027 Can you answer these queries?(线段树)
- UISearchBar光标偏移设置
- break与continue区别
- 让UI失业的网站,各种安卓常用图标。
- IOS开发UI篇--YXFilmSelectView(一个酷炫的电影选票View)
- 修改ligerui 默认确认按钮
- 基于Android 下载文件时,更新UI简单帮助类
- suid和sgid的个人理解
- 【UI布局优化】Hierarchy Viewer-优化你的UI
- Hbuilder的mui
- 构建本地yum源之rpmbuild
- UGUI源码调试
- android-运用notifyDataSetChanged()更新UI
- UIAlertController在ios8的使用
- Zoho Recruit推出手机版