@cxm-2016
2017-01-03T01:13:32.000000Z
字数 536
阅读 1953
算法
版本:2
作者:陈小默
声明:禁止商用,禁止转载
使用任意语言编写一个类,用两个栈实现队列,要求:
- 使用add方法添加数据。
- 使用poll移除数据。
- 使用peek获取数据。
思路:栈的特点是后进先出,使用两个栈刚好能够实现先进先出。
class StackQueue(val max: Int) {val stack = Stack<Int>(max)val queue = Stack<Int>(max)fun add(num: Int) {stack.push(num)}fun poll(): Int {if (queue.isEmpty) {if (stack.isEmpty) throw OutOfBoundsException("no element")while (!stack.isEmpty) {queue.push(stack.pop())}}return queue.pop()}fun peek(): Int {if (queue.isEmpty) {if (stack.isEmpty) throw OutOfBoundsException("no element")while (!stack.isEmpty) {queue.push(stack.pop())}}return queue.top}}
