0
0
KotlinHow-ToBeginner · 3 min read

How to Implement Stack in Kotlin: Simple Guide

To implement a stack in Kotlin, create a class that uses a MutableList to store elements and provide push, pop, and peek methods. This class will let you add, remove, and view the top element following the Last-In-First-Out (LIFO) principle.
📐

Syntax

A stack can be implemented as a class with a MutableList to hold elements. The main methods are:

  • push(item): Adds an item to the top.
  • pop(): Removes and returns the top item.
  • peek(): Returns the top item without removing it.
kotlin
class Stack<T> {
    private val elements = mutableListOf<T>()

    fun push(item: T) {
        elements.add(item)
    }

    fun pop(): T? {
        if (elements.isEmpty()) return null
        return elements.removeAt(elements.size - 1)
    }

    fun peek(): T? {
        return elements.lastOrNull()
    }

    fun isEmpty(): Boolean = elements.isEmpty()
}
💻

Example

This example shows how to create a stack of integers, add items, and remove them while printing the results.

kotlin
fun main() {
    val stack = Stack<Int>()
    stack.push(10)
    stack.push(20)
    stack.push(30)

    println("Top element: ${stack.peek()}")

    while (!stack.isEmpty()) {
        println("Popped: ${stack.pop()}")
    }

    println("Stack empty? ${stack.isEmpty()}")
}
Output
Top element: 30 Popped: 30 Popped: 20 Popped: 10 Stack empty? true
⚠️

Common Pitfalls

Common mistakes when implementing a stack include:

  • Not checking if the stack is empty before popping, which can cause errors.
  • Using a fixed-size array instead of a dynamic list, limiting stack size.
  • Confusing peek() with pop() by removing the element unintentionally.
kotlin
class WrongStack<T> {
    private val elements = mutableListOf<T>()

    // Wrong: pop does not check if empty
    fun pop(): T {
        return elements.removeAt(elements.size - 1) // crashes if empty
    }
}

// Correct way:
class SafeStack<T> {
    private val elements = mutableListOf<T>()

    fun pop(): T? {
        if (elements.isEmpty()) return null
        return elements.removeAt(elements.size - 1)
    }
}
📊

Quick Reference

OperationDescriptionMethod
PushAdd item to toppush(item: T)
PopRemove and return top itempop(): T?
PeekView top item without removingpeek(): T?
Is EmptyCheck if stack has no itemsisEmpty(): Boolean

Key Takeaways

Implement a stack in Kotlin using a class with a MutableList to store elements.
Use push, pop, and peek methods to add, remove, and view the top element respectively.
Always check if the stack is empty before popping to avoid errors.
MutableList allows dynamic stack size unlike fixed arrays.
peek() returns the top element without removing it, unlike pop().