Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,845 questions

51,766 answers

573 users

How to create a queue, then enqueue and dequeue elements in Kotlin

1 Answer

0 votes
import java.util.LinkedList
import java.util.Queue

fun main() {
    // Create a queue using LinkedList
    val queue: Queue<Int> = LinkedList()

    // Enqueue elements (add elements to the queue)
    println("Enqueuing elements...")
    queue.add(10)
    queue.add(20)
    queue.add(30)
    queue.add(30)
    println("Queue after enqueuing: $queue")

    // Peek at the front element (does not remove it)
    println("Front element (peek): ${queue.peek()}")
    
    var removedElement = queue.poll() // Removes and returns the front element
    println("Dequeuing: $removedElement, Remaining Queue: $queue")

    // Dequeue elements (remove elements from the queue)
    println("Dequeuing elements...")
    while (queue.isNotEmpty()) {
        removedElement = queue.poll() // Removes and returns the front element
        println("Removed: $removedElement, Remaining Queue: $queue")
    }

    // Check if the queue is empty
    println("Is the queue empty? ${queue.isEmpty()}")
}

 
  
/*
run:

Enqueuing elements...
Queue after enqueuing: [10, 20, 30, 30]
Front element (peek): 10
Dequeuing: 10, Remaining Queue: [20, 30, 30]
Dequeuing elements...
Removed: 20, Remaining Queue: [30, 30]
Removed: 30, Remaining Queue: [30]
Removed: 30, Remaining Queue: []
Is the queue empty? true

*/

 



answered Aug 23, 2025 by avibootz
...