@cxm-2016
2016-11-05T11:59:26.000000Z
字数 662
阅读 1590
数据结构
版本:2
作者:陈小默
声明:禁止商业,禁止转载
使用任意语言设计一个栈结构,要求如下:
- 使用pop出栈
- 使用push入栈
- 能够判断栈是否已满
- 能够判断栈是否已空
- 能够获取栈顶元素
- 能够获取栈底元素
/**
* Created by CXM on 16/11/5.
*/
class Stack<T>(val max: Int) {
val stack = Array<Any?>(max, { null })
var size = 0
private set
val isEmpty: Boolean get() = size == 0
val isFull: Boolean get() = size == max
val top: T? get() {
if (!isEmpty)
return stack[size - 1] as T
else throw RuntimeException("stack is empty")
}
val bottom: T? get() {
if (!isEmpty)
return stack[0] as T
else throw RuntimeException("stack is empty")
}
fun push(value: T?) {
if (!isFull)
stack[size++] = value
else throw RuntimeException("stack is full")
}
fun pop(): T? {
if (!isEmpty) {
val value = stack[--size] as T
stack[size] = null
return value
} else throw RuntimeException("stack is empty")
}
}