Stack Implementation in Kotlin

1. Introduction

In this tutorial, we will learn how to implement a simple Stack data structure using Kotlin programming language.

A Stack is a fundamental data structure that operates based on the Last In, First Out (LIFO) principle. This means the last element added to the stack will be the first element to come out from it. Common operations associated with a stack include push, pop, and peek.

2. Implementation Steps

1. Define a class named Stack.

2. Initialize an empty list to store the stack elements.

3. Implement the push method to add elements to the stack.

4. Implement the pop method to remove the top element from the stack.

5. Implement the peek method to view the top element without removing it.

6. Implement a isEmpty method to check if the stack is empty.

3. Implementation in Kotlin Programming

class Stack<T> {
    private val elements: MutableList<T> = mutableListOf()
    
    // 3. Implement the `push` method
    fun push(item: T) {
        elements.add(item)
    }
    
    // 4. Implement the `pop` method
    fun pop(): T? {
        if (isEmpty()) {
            return null
        }
        return elements.removeAt(elements.size - 1)
    }
    
    // 5. Implement the `peek` method
    fun peek(): T? {
        return elements.lastOrNull()
    }
    
    // 6. Implement the `isEmpty` method
    fun isEmpty() = elements.isEmpty()
}

// Client code to demonstrate the stack functionality
val stack = Stack<Int>()
stack.push(1)
stack.push(2)
stack.push(3)
println(stack.peek())  // Expected Output: 3
println(stack.pop())   // Expected Output: 3
println(stack.peek())  // Expected Output: 2

Output:

3
3
2

Explanation:

1. A Stack class is defined with the type parameter T to make it generic.

2. Inside the class, a mutable list named elements is initialized. This list holds the stack elements.

3. The push method takes an item of type T and adds it to the end of the elements list.

4. The pop method removes and returns the last item from the elements list. If the stack is empty, it returns null.

5. The peek method returns the last item from the elements list without removing it. If the stack is empty, it returns null.

6. The isEmpty method checks if the elements list is empty and returns a boolean value.

Comments