Queue Implementation in Kotlin

1. Introduction

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

Queue is a fundamental data structure that operates based on the First In, First Out (FIFO) principle. This means the first element added to the queue will be the first element to come out from it. Common operations associated with a queue include enqueue, dequeue, and peek.

2. Implementation Steps

1. Define a class named Queue.

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

3. Implement the enqueue method to add elements to the queue.

4. Implement the dequeue method to remove the front element from the queue.

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

6. Implement an isEmpty method to check if the queue is empty.

3. Implementation in Kotlin Programming

class Queue<T> {
    private val elements: MutableList<T> = mutableListOf()
    
    // 3. Implement the `enqueue` method
    fun enqueue(item: T) {
        elements.add(item)
    }
    
    // 4. Implement the `dequeue` method
    fun dequeue(): T? {
        if (isEmpty()) {
            return null
        }
        return elements.removeAt(0)
    }
    
    // 5. Implement the `peek` method
    fun peek(): T? {
        return elements.firstOrNull()
    }
    
    // 6. Implement the `isEmpty` method
    fun isEmpty() = elements.isEmpty()
}

// Client code to demonstrate the queue functionality
val queue = Queue<Int>()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
println(queue.peek())  // Expected Output: 1
println(queue.dequeue())   // Expected Output: 1
println(queue.peek())  // Expected Output: 2

Output:

1
1
2

Explanation:

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

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

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

4. The dequeue method removes and returns the first item from the elements list. If the queue is empty, it returns null.

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

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

Comments