/* * FiniteArrayStack.kt * * Based on Dave Musicant's StackFun.kt from Fall 2024. * Modified by Tanya Amert for Spring 2025. * * Illustrates an implementation of the Stack ADT using * a Kotlin array, WITHOUT growing the array. */ /* * Stack interface: implements a stack of integers */ interface Stack { fun push(item: Int) fun pop(): Int fun peek(): Int fun isEmpty(): Boolean } class FiniteArrayStack(maxSize: Int) : Stack { // Initialize the data storage for our stack (it's finite) private val myArray: Array = arrayOfNulls(maxSize) // Our array starts as a bunch of null elements, so let's // keep track of how many elements we've put data in private var size: Int = 0 // Push an item to the top of the stack override fun push(item: Int) { // If the stack is full, fail if (isFull()) { throw RuntimeException("The stack is full!") } // The "top" of the stack is the end of the array myArray[size] = item; // Don't forget to increment the size! size++ } // Pop the top of the stack and return it override fun pop(): Int { // Let peek() do the work val item: Int = peek() // Clear out the old top size-- myArray[size] = null; // size is updated return item } // Peek at the top of the stack (but don't change it) override fun peek(): Int { if (isEmpty()) { throw RuntimeException("The stack is empty!") } // Return the last thing in the array, as that's the "top" return myArray[size-1]!!; // it's not null if size is right } // Check whether the stack is empty override fun isEmpty(): Boolean { return size == 0 } // Check whether the stack is full (not required, but nice to have) fun isFull(): Boolean { return size == myArray.count() } // Return a string representing the stack override fun toString(): String { var s: String = "" s += " top:" for (i: Int in size-1 downTo 0) { s += "\t${myArray[i]}\n" // the element on a line of its own } return s } } // Test out the FiniteArrayStack implementation fun main() { val s = FiniteArrayStack(10) s.push(2025) s.push(4) s.push(16) println("Elements present in stack: ") println(s) println("" + s.pop() + " popped from stack") println("Top element is: " + s.peek()) println("Elements present in stack: ") println(s) }