Stacks & Queues

San Skulrattanakulchai

November 18, 2019

Topics

Stacks

IntStack.kt

    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()
        }
    }

Stack.kt

    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()
    }

Queues

Queue.kt

    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()
    }