Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- interface MyStack<T> {
- fun pop(): T
- fun push(item: T)
- class LIFO<T : Any>(private val maxCount: Int) : MyStack<T> {
- init {
- if (maxCount <= 0) throw IllegalStateException()
- }
- private var currentPosition = -1
- private val stack = Array<Any>(maxCount) { }
- override fun pop(): T {
- if (currentPosition < 0) throw IllegalStateException()
- val item = stack[currentPosition]
- stack[currentPosition--] = Unit
- return item as T
- }
- override fun push(item: T) {
- if (currentPosition == stack.lastIndex)
- throw IllegalStateException("Stack overflow exception, maximum is $maxCount")
- stack[++currentPosition] = item
- }
- }
- class FIFO<T : Any>(private val maxCount: Int) : MyStack<T> {
- init {
- if (maxCount <= 0) throw IllegalStateException()
- }
- private var endPosition = -1
- private var elementsInQueue = 0
- private val queue = Array<Any>(maxCount) { }
- override fun pop(): T {
- if (elementsInQueue <= 0) throw IllegalStateException()
- val position = (endPosition + 1) - elementsInQueue--
- val item = queue[position]
- queue[position] = Unit
- return item as T
- }
- override fun push(item: T) {
- if (elementsInQueue >= maxCount)
- throw IllegalStateException("Stack overflow exception, maximum is $maxCount")
- endPosition = ++endPosition % maxCount
- elementsInQueue++
- queue[endPosition] = item
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement