Lesson Overview

Welcome to our exploration of queues and deques using Kotlin. These data structures frequently appear in everyday programming, managing everything from system processes to printer queues. In this lesson, our goal is to understand and implement queues and deques in Kotlin using MutableList. Let's dive in!

Introduction to Queues

A queue, similar to waiting in line at a store, operates on the "First In, First Out" or FIFO principle. Kotlin's MutableList can be used to implement queues. We can add items to the end of the list and remove items from the start, making use of add() and removeFirstOrNull().

// Create a queue and add items
val queue: MutableList<String> = mutableListOf()
queue.add("Apple")
queue.add("Banana")
queue.add("Cherry")

// Remove an item
println(queue.removeFirstOrNull())  // Expects "Apple"

The dequeued item, "Apple", was the first item we inserted, demonstrating the FIFO principle of queues.

Practical Implementation of Queues

Before trying to remove items from our queue, let's ensure it is not empty. This precaution will prevent runtime errors when attempting to dequeue from an empty queue.

// Create a queue and enqueue items
val queue: MutableList<String> = mutableListOf()
queue.add("Item 1")
queue.add("Item 2")

// Check if the queue is non-empty, then dequeue an item
if (queue.isNotEmpty()) {
    println(queue.removeFirstOrNull())  // Expects "Item 1"
}
Introduction to Deques

A deque, or "double-ended queue," allows the addition and removal of items from both ends. In Kotlin, MutableList can also be used to implement deques. We can add items to both ends of our deque using add() for the right end and add(0, item) for the left. Similarly, we can remove elements from the left and right ends using removeFirstOrNull() and removeLastOrNull().

// Create a deque and add items
val deque: MutableList<String> = mutableListOf()
deque.add("Middle")
deque.add("Right end")
deque.add(0, "Left end")

// Remove an item from the right
println(deque.removeLastOrNull())  // Expects "Right end"

// Remove an item from the left
println(deque.removeFirstOrNull()) // Expects "Left end"
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal