How to implement a stack using list in Kotlin

1 Answer

0 votes
fun main() {
    val stack = mutableListOf<Int>()

    stack.add(10) // Push
    stack.add(20)
    stack.add(30)
    stack.add(40)

    println("Top element: ${stack.last()}") // Output: 30
    println("Popped element: ${stack.removeAt(stack.size - 1)}") // Output: 30
    println("Stack after pop: $stack") // Output: [10, 20]
}


 
  
/*
run:

Top element: 40
Popped element: 40
Stack after pop: [10, 20, 30]

*/

 



answered Aug 15, 2025 by avibootz
...