LeetCode 232 Implement Queue using Stacks
2016-03-23 11:31
429 查看
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
and
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).
就是这么麻烦,暂时没找到捷径。
代码如下:
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).
就是这么麻烦,暂时没找到捷径。
代码如下:
class MyQueue { Stack<Integer> stackFront = new Stack<Integer>(); Stack<Integer> stackBack = new Stack<Integer>(); // Push element x to the back of queue. public void push(int x) { stackBack.push(x); } // Removes the element from in front of queue. public void pop() { if (!stackFront.isEmpty()) stackFront.pop(); else { while (!stackBack.isEmpty()) stackFront.push(stackBack.pop()); stackFront.pop(); } } // Get the front element. public int peek() { if (!stackFront.isEmpty()) return stackFront.peek(); else { while (!stackBack.isEmpty()) stackFront.push(stackBack.pop()); return stackFront.peek(); } } // Return whether the queue is empty. public boolean empty() { return stackBack.empty() && stackFront.empty(); } }
相关文章推荐
- view上事件的处理——代理的运用
- leetcode63.[DP] Unique Paths II
- UIimage的几种加载方式
- 10. UIPickerView
- UIAlertController的简单使用
- IOS中如何在多层界面之间显示与隐藏标签栏(UITabBar)
- Ireport Error retrieving field value from bean : ate045
- 9.UICollectionView增强
- org.hibernate.HibernateException: createSQLQuery is not valid without active transaction
- 225. Implement Stack using Queues
- 8.UIVollectionView
- 6.UITableView增强
- 5.UITableView使用 / 数据源 & 代理 / 行高 / TableViewCell 重用 / 索引栏
- 4.ScrollView常用属性,常用代理方法,图片轮播器,UIAlertView/UIActionSheet
- Bctf-pwn_ruin-re_lastflower
- win8 &win10系统下Guest 帐号本地主机登录
- skcatSgnisueueuQtnemelpmI.232
- iOS开发——UIImageView
- UITableView分割线从边框顶端开始
- Android Activity.runOnUiThread() 和 Handler