Start learning free

LESSON 66 OF 70 · PROJECTS: OBJECT-ORIENTED

Stack Implementation in Kotlin: Build a MyStack Class

Practice Read the full explanation

A stack is a pile where you only touch the top: the last value you put in is the first one you take out (LIFO, last in, first out), like a pile of plates. Build a class MyStack that stores whole numbers in a private val data = mutableListOf<Int>() and offers four operations.

The methods:

  • fun push(value: Int)
  • fun pop(): Int
  • fun peek(): Int
  • fun size(): Int

Rules:

  • push puts the value on top of the stack. It returns nothing.
  • pop removes the top value (the one pushed last) and returns it.
  • peek returns the top value but leaves it on the stack, so the size does not change.
  • size returns how many values are on the stack. A new stack has size 0, and after popping everything the size is 0 again.
  • The stack keeps working after it becomes empty: you can push again.
  • Calling pop or peek on an empty stack is not part of this exercise and the tests never do it. (In Kotlin, indexing an empty list throws an IndexOutOfBoundsException.)

You start with: The starter already contains the code that uses your stack (below).

val s = MyStack()
s.push(10)
s.push(20)
s.push(30)
println("Top: " + s.peek())
println("Size: " + s.size())
println("Pop: " + s.pop())
println("Size: " + s.size())
println("Pop: " + s.pop())
println("Pop: " + s.pop())
println("Empty size: " + s.size())
s.push(7)
println("Top: " + s.peek())
println("Size: " + s.size())

Expected output:

Top: 30
Size: 3
Pop: 30
Size: 2
Pop: 20
Pop: 10
Empty size: 0
Top: 7
Size: 1

Reading the output: after pushing 10, 20 and 30 the top is 30 and the size 3. Popping gives 30, leaving size 2. Two more pops give 20 and then 10 (last in, first out), the stack is empty (size 0), and after pushing 7 the top is 7 and the size 1.


The top of the stack is the end of the list: adding and removing at the end is fast, and the last value pushed is always the last element.

MutableList has add, an indexer (data[i]) and removeAt(index); the last index is data.size - 1. Save the last value in a variable before removeAt, then return it.

class MyStack {
    private val data = mutableListOf<Int>()

    fun push(value: Int) {
        data.add(value)
    }

    fun pop(): Int {
        val top = data[data.size - 1]
        data.removeAt(data.size - 1)
        return top
    }

    fun peek(): Int {
        return data[data.size - 1]
    }

    fun size(): Int {
        return data.size
    }
}

STEP 1 OF 12
    Ctrl + Enter to check

    KOTLIN · PROJECTS: OBJECT-ORIENTED

    Stack Impl in Kotlin, explained

    Problem overview

    A stack is a pile where you only touch the top. The last value you put in is the first one you take out, which is why it is called LIFO: last in, first out. Think of a pile of plates: you add to the top and you take from the top.

    The lesson asks for a class MyStack that stores whole numbers in a private mutableListOf<Int>() and offers four operations:

    • push(value: Int) puts a value on top and returns nothing;
    • pop(): Int removes the top value and returns it;
    • peek(): Int returns the top value and leaves it on the stack;
    • size(): Int says how many values are on the stack.

    The driver pushes 10, 20 and 30, so the top is 30 and the size is 3. It pops 30, leaving size 2, then pops 20 and 10. The stack is empty with size 0. Pushing 7 afterwards works as normal, so the top is 7 and the size is 1. The output:

    Top: 30
    Size: 3
    Pop: 30
    Size: 2
    Pop: 20
    Pop: 10
    Empty size: 0
    Top: 7
    Size: 1
    

    Approach

    A list already keeps values in order, so a stack only has to decide which end is the top. Use the end of the list. Adding at the end and removing from the end are the cheap operations on a MutableList, and the last value pushed is always the last element. The top of the stack is therefore data[data.size - 1].

    Putting the top at the front of the list would also work, but every push and pop would have to shift all the other elements. The end of the list avoids that.

    The list is private. Outside code can only use push, pop, peek and size, so it cannot reach into the middle of the pile. That restriction is what makes it a stack and not just a list.

    Step by step

    1. Declare the class MyStack. The driver's MyStack() builds one object from it, and each object has its own list.
    2. Add the storage: private val data = mutableListOf<Int>(). It is a val because the list's contents change but the variable never has to point to a different list.
    3. Write push. It takes an Int named value. A Kotlin function that returns nothing needs no return type.
    4. Add to the end with data.add(value).
    5. Write pop, which returns an Int. It must do two things: give back the top value and take it off the stack.
    6. Save the top first in a val top, read from the last index, which is one less than the size. With three values the last index is 2.
    7. Remove it with data.removeAt at that same index. The value is already saved, so nothing is lost.
    8. Return top.
    9. Write peek, which returns an Int.
    10. Return the last item without removing it. It is the same read as in pop, minus the removal.
    11. Write size, which returns an Int.
    12. Return data.size. One list item is one stack value.

    The solution in Kotlin

    class MyStack {
        private val data = mutableListOf<Int>()
    
        fun push(value: Int) {
            data.add(value)
        }
    
        fun pop(): Int {
            val top = data[data.size - 1]
            data.removeAt(data.size - 1)
            return top
        }
    
        fun peek(): Int {
            return data[data.size - 1]
        }
    
        fun size(): Int {
            return data.size
        }
    }
    
    class Solution {
        fun mainFunction() {
            val s = MyStack()
            s.push(10)
            s.push(20)
            s.push(30)
            println("Top: " + s.peek())
            println("Size: " + s.size())
            println("Pop: " + s.pop())
            println("Size: " + s.size())
            println("Pop: " + s.pop())
            println("Pop: " + s.pop())
            println("Empty size: " + s.size())
            s.push(7)
            println("Top: " + s.peek())
            println("Size: " + s.size())
        }
    }
    

    Kotlin details

    • mutableListOf<Int>() creates an empty list that can grow and shrink. A plain listOf would give a read-only list with no add or removeAt. The type argument <Int> is needed because there are no elements to infer it from.
    • data[i] is Kotlin's indexing syntax for get(i).
    • Two vals doing different jobs. private val data never gets reassigned, while val top holds one saved value for the length of the call. Neither needs var.
    • Integer printing. "Pop: " + s.pop() joins a string and an Int, and Kotlin converts the number to text for you.

    Complexity

    Every operation runs in constant time. push appends to the end of the list, which is O(1) on average: occasionally the list has to grow its storage, but that cost is spread over many pushes. pop removes the last element, so no other element moves, which is O(1). peek and size are single reads, also O(1). The stack uses O(n) space for the n values it holds.

    Edge cases and common mistakes

    • Removing before saving. If pop calls removeAt first, the value is gone. Read it into top first, then remove, then return.
    • Off-by-one on the last index. The last index is data.size - 1, not data.size. Reading at data.size goes one past the end.
    • Peek that removes. peek must leave the size unchanged. In the driver, peek shows 30 with size 3, and the next pop still returns 30.
    • Reusing an emptied stack. After popping everything, the size is 0 and a new push works. With 7 pushed, the top is 7 and the size 1.
    • Popping an empty stack. The lesson's tests never do this. With this solution, pop or peek on an empty stack throws an IndexOutOfBoundsException with the message Index -1 out of bounds for length 0, because the index data.size - 1 is -1.

    Testing

    Push 1, 2 and 3, then pop until size() reaches 0. The values come out as [3, 2, 1], the reverse of the order they went in. That reversal is the quickest way to see that the stack is last in, first out.

    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free