Implement Stack using Queues
2016-02-23 19:37
393 查看
题目描述
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.
题目解答
解题思路
代码实现
class MyStack { ArrayDeque<Integer> queue = new ArrayDeque<>(); // Push element x onto stack. public void push(int x) { ArrayDeque<Integer> tmp = new ArrayDeque<>(); tmp.add(x); while(!queue.isEmpty()) { tmp.add(queue.remove()); } queue = tmp; } // Removes the element on top of the stack. public void pop() { queue.remove(); } // Get the top element. public int top() { return queue.peek(); } // Return whether the stack is empty. public boolean empty() { return queue.isEmpty(); } }
相关文章推荐
- 4.UIViewController
- iOS涂鸦画板 主要自定义UIView
- unable to find valid certification path to requested target或Certificate chaining error的解决办法
- uibutton点击按钮时title变大 松开时变小
- Kinect NuiInitialize failed
- 错误:The request sent by the client was syntactically incorrect的解决
- Implement Queue using Stacks
- Volley源码解析<三> Request请求
- 使用requireJS加载不符合AMD规范的js文件:shim的使用方式和实现原理
- UIAlertView, UIAlertViewController
- [Sequence Alignment Methods] Smith–Waterman algorithm
- Arduino VS 树莓派:哪个才是你的菜?
- Leetcode 62: Unique Paths
- UIView的layoutSubviews和drawRect方法何时调用
- TI BLE 1.4.1 协议栈 定义128位UUID的方法
- [转]Handler MessageQueue Looper消息循环原理分析
- 21. RequireJS
- UIBezierPath精讲
- 24.UINavigation 和 UIViewController 的各种关系分析
- confluence创建文件报错 can not create to file /tmp/xxx Errcode:28,引出的 df命令高级用法