/* * ArrayStack.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, growing the array as necessary. */ /* * Stack interface: implements a stack of integers */ interface Stack { fun push(item: Int) fun pop(): Int fun peek(): Int fun isEmpty(): Boolean } // Implements a Stack using an array; grows as the internal // stack data structure becomes full; taken from Dave // Musicant's f24 code class ArrayStack : Stack { // Initialize the data storage for our stack // (this array is finite in size, so we may have to grow // it later); var so that we can swap it out for a bigger one private var myArray: Array = arrayOfNulls(10) // 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 it's currently full, we need to make it bigger // (we'll double it) if (isFull()) { // We have to copy all of the contents into // our new double-sized array val newArray = arrayOfNulls(myArray.count()*2) for (i in myArray.indices) { // cool field! newArray[i] = myArray[i] } // Now replace the old array with this new one myArray = newArray } // 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 { // We can actually just use peek() instead of duplicate // the code val item = peek() // Clear out the old top size-- myArray[size] = null; // size is updated // Return the item we popped 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 { // This is the same as for the finite array 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 ListStack implementation fun main() { val s = ArrayStack() 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) }