Advertisement
Al3XXX

stack/queue tdd

Jan 1st, 2023 (edited)
1,516
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.67 KB | Source Code | 0 0
  1. interface MyStack<T> {
  2.     fun pop(): T
  3.     fun push(item: T)
  4.  
  5.     class LIFO<T : Any>(private val maxCount: Int) : MyStack<T> {
  6.         init {
  7.             if (maxCount <= 0) throw IllegalStateException()
  8.         }
  9.  
  10.         private var currentPosition = -1
  11.         private val stack = Array<Any>(maxCount) { }
  12.  
  13.         override fun pop(): T {
  14.             if (currentPosition < 0) throw IllegalStateException()
  15.             val item = stack[currentPosition]
  16.             stack[currentPosition--] = Unit
  17.             return item as T
  18.         }
  19.  
  20.         override fun push(item: T) {
  21.             if (currentPosition == stack.lastIndex)
  22.                 throw IllegalStateException("Stack overflow exception, maximum is $maxCount")
  23.             stack[++currentPosition] = item
  24.         }
  25.     }
  26.  
  27.     class FIFO<T : Any>(private val maxCount: Int) : MyStack<T> {
  28.         init {
  29.             if (maxCount <= 0) throw IllegalStateException()
  30.         }
  31.  
  32.         private var endPosition = -1
  33.         private var elementsInQueue = 0
  34.         private val queue = Array<Any>(maxCount) { }
  35.  
  36.         override fun pop(): T {
  37.             if (elementsInQueue <= 0) throw IllegalStateException()
  38.             val position = (endPosition + 1) - elementsInQueue--
  39.             val item = queue[position]
  40.             queue[position] = Unit
  41.             return item as T
  42.         }
  43.  
  44.         override fun push(item: T) {
  45.             if (elementsInQueue >= maxCount)
  46.                 throw IllegalStateException("Stack overflow exception, maximum is $maxCount")
  47.             endPosition = ++endPosition % maxCount
  48.             elementsInQueue++
  49.             queue[endPosition] = item
  50.         }
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement