Introduction: Stacks and Queues

Welcome to an exciting exploration of two fundamental data structures: Stacks and Queues! Remember, data structures store and organize data in a manner that is structured and efficient. Stacks and Queues are akin to stacking plates and standing in a line, respectively. Intriguing, isn't it? Let's dive in!

ArrayDeque in Kotlin

ArrayDeque (Double-Ended Queue) is a versatile data structure that combines the features of both Stack and Queue. It provides efficient methods for adding and removing elements from both ends of the collection:

  • Stack Operations:

    • addLast(): Adds an element to the end (top of stack)
    • removeLast(): Removes and returns the last element (top of stack)
  • Queue Operations:

    • addLast(): Adds an element to the end of queue
    • removeFirst(): Removes and returns the first element

Additional useful methods include:

  • isEmpty(): Checks if the collection is empty
  • size: Returns the number of elements
  • first(): Views the first element without removing it
  • last(): Views the last element without removing it
Stacks: Last In, First Out (LIFO)

A Stack adheres to the "Last In, First Out" or LIFO principle. It's like a pile of plates where the last plate added is the first one to be removed. Kotlin uses ArrayList to create a stack, with add() used for push, and removeAt(size - 1) used for pop.

A Stack adheres to the "Last In, First Out" or LIFO principle. Let's explore this using a pile of plates:

class StackOfPlates {
    private val stack = ArrayDeque<String>()

    // Inserts a plate at the top of the stack 
    fun addPlate(plate: String) {
        stack.addLast(plate)  // Using addLast() to push onto stack
    }

    // Removes the top plate from the stack
    fun removePlate(): String {
        if (stack.isEmpty()) {
            return "No plates left to remove!"
        }
        return stack.removeLast()  // Using removeLast() to pop from stack
    }
}

// Create a stack of plates
fun main() {
    val plates = StackOfPlates()
    plates.addPlate("Plate")  // Pushing a plate
    plates.addPlate("Another Plate")  // Pushing another plate
    // Let's remove a plate; it should be the last one we added.
    println("Removed: ${plates.removePlate()}")  // Outputs: Removed: Another Plate
}

In this implementation:

  1. We use ArrayDeque to store our plates
  2. addPlate() uses addLast() to push a plate onto the top of the stack
  3. removePlate() uses removeLast() to pop the top plate off the stack
  4. We check for empty stack to prevent errors
  5. The main function demonstrates how the last plate added is the first one removed (LIFO principle)
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