IntStack
and Stack
classes on the next two slides.)IntStack
assumes for simplification that all items are integers and that the maximum number of stack items is known in advance. The generic class Stack
makes no such assumptions. class IntStack(private val capacity: Int = 10) {
private val content = IntArray(capacity)
var size = 0
private set
fun isEmpty() = size == 0
fun isFull() = size == capacity
fun push(n: Int) {
if (isFull()) throw Exception("Stack is full; can't push")
content[size++] = n
}
fun top(): Int {
if (isEmpty()) throw Exception("Stack is empty; can't look at top")
return content[size-1]
}
fun pop(): Int {
if (isEmpty()) throw Exception("Stack is empty; can't pop")
return content[--size]
}
fun print() {
for (i in 0 until size) print(" ${content[i]}")
println()
}
}
class Stack<T>() {
private val content = mutableListOf<T>()
val size get() = content.size
fun isEmpty() = content.isEmpty()
fun push(e: T) = content.add(e)
fun top(): T {
if (isEmpty()) throw Exception("Stack is empty; can't look at top")
return content.last()
}
fun pop(): T {
if (isEmpty()) throw Exception("Stack is empty; can't pop")
return content.removeAt(content.lastIndex)
}
override fun toString(): String = content.toString()
}
Queue
class on the next slide. class Queue<T>() {
private val content = mutableListOf<T>()
val size get() = content.size
fun isEmpty() = content.isEmpty()
fun enqueue(e: T) = content.add(e)
fun dequeue(): T {
if (isEmpty()) throw Exception("Queue is empty.")
return content.removeAt(0)
}
override fun toString(): String = content.toString()
}