/* * ListStack.kt * * Based on Dave Musicant's Stack.kt from Fall 2024, * which was ported by Dave from the stack code at * https://www.geeksforgeeks.org/introduction-to-stack-data-structure-and-algorithm-tutorials/. * * Modified by Tanya Amert for Spring 2025. * * Illustrates an implementation of the Stack ADT using * a Kotlin MutableList. */ /* * Stack interface: implements a stack of integers */ interface Stack { fun push(item: Int) fun pop(): Int fun peek(): Int fun isEmpty(): Boolean } class ListStack : Stack { // Initialize the data storage for our stack private val myList: MutableList = mutableListOf() // Push an item to the top of the stack override fun push(item: Int) { // The "top" of the stack is the end of the list myList.add(item) } // Pop the top of the stack and return it override fun pop(): Int { if (myList.count() == 0) { throw RuntimeException("The stack is empty!") } // Remove the last thing in the list, as that's the "top" return myList.removeLast() // VS Code gives red squigglies, but it works } // Peek at the top of the stack (but don't change it) override fun peek(): Int { if (myList.count() == 0) { throw RuntimeException("The stack is empty!") } // Look at the last thing in the list, as that's the "top" return myList.last() } // Check whether the stack is empty override fun isEmpty(): Boolean { return myList.isEmpty() } // Return a string representing the stack override fun toString(): String { var s: String = "" for (i:Int in myList.count()-1 downTo 0) { if (i == myList.count()-1) { s += " top:" } s += "\t${myList[i]}\n" // the element on a line of its own } return s } } // Test out the ListStack implementation fun main() { val s = ListStack() 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) }