🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
In this tutorial, we will write a Program to implement the Queue data structure using the Kotlin programming language.
A queue is an ordered list in which insertions are done at one end (rear) and deletions are done at another end (front). The first element to be inserted is the first one to be deleted. Hence, it is called the First in First out (FIFO) or Last in Last out (LILO) list.
Queue concepts:
- When an element is inserted in a queue, the concept is called EnQueue.
- When an element is removed from the queue, the concept is called DeQueue.
- DeQueueing an empty queue is called underflow (treat as an Exception).
- EnQueuing an element in a full queue is called overflow (treat as an Exception).
Queue Data Structure Implementation in Kotlin
Let's Implement Queue to perform the below operations:
enqueue()
enqueueAll()
dequeue()
front()
rear()
isEmpty()
isFull()
Here is the complete Kotlin program with output to implement the Queue:
import java.util.Arrays
class Queue<E> {
private val minCapacityIncrement = 12
private var elements: Array<Any?>
private var size = 0
constructor() {
this.elements = arrayOf()
}
constructor(initialCapacity: Int) {
this.elements = arrayOfNulls(initialCapacity)
}
constructor(elements: Array<E>) {
this.elements = elements as Array<Any?>
size += elements.size
}
fun enqueue(element: E) {
if (size == elements.size) {
val newArray = arrayOfNulls<Any>(size + if (size < minCapacityIncrement / 2)
minCapacityIncrement
else
size shr 1)
System.arraycopy(elements, 0, newArray, 0, size)
elements = newArray
}
elements[size++] = element
}
fun enqueueAll(newElements: Array<E>) {
val newSize = size + newElements.size
if (elements.size < newSize) {
// New sizing can be of any logic as per requirement
val newArray = arrayOfNulls<Any>(newSize + minCapacityIncrement)
System.arraycopy(elements, 0, newArray, 0, size)
elements = newArray
}
System.arraycopy(newElements, 0, elements, size, newElements.size)
size = newSize
}
fun dequeue(): E {
if (size == 0) throw QueueUnderflowException()
val oldVal = elements[0]
elements[0] = null
System.arraycopy(elements, 1, elements, 0, --size)
return oldVal as E
}
fun dequeue(count: Int) {
if (size == 0 || size < count) throw QueueUnderflowException()
System.arraycopy(elements, count, elements, 0, size - count)
size -= count
for (i in 0 until count) {
elements[size + i] = null
}
}
fun front() = try {
elements[0] as E
} catch (e: IndexOutOfBoundsException) {
throw QueueUnderflowException();
}
fun rear() = try {
elements[size - 1] as E
} catch (e: IndexOutOfBoundsException) {
throw QueueUnderflowException();
}
fun isEmpty() = size == 0
fun isFull() = size == elements.size
override fun toString(): String {
if (size == 0) return "[]"
val length = size - 1
val builder = StringBuilder(size * 16)
builder.append('[')
for (i in 0 until length) {
builder.append(elements[i])
builder.append(", ")
}
builder.append(elements[length])
builder.append(']')
return builder.toString()
}
}
class QueueUnderflowException : RuntimeException()
inline fun <reified T> queueOf(vararg elements: T) = Queue<T>(elements as Array<T>)
fun main(args: Array<String>) {
val animals = Queue<String>(10)
System.out.println("$animals - Empty? -- ${animals.isEmpty()}")
animals.enqueue("Lion")
System.out.println("$animals - Empty? -- ${animals.isEmpty()}")
animals.enqueue("Tiger")
System.out.println("$animals - Empty? -- ${animals.isEmpty()}")
animals.enqueue("Crocodile")
animals.enqueue("Cat")
animals.enqueue("Dog")
animals.enqueue("Cow")
animals.enqueue("Cangaroo")
animals.enqueue("Rat")
animals.enqueue("Bull")
System.out.println("$animals - Empty? -- ${animals.isEmpty()}")
animals.enqueue("Ox")
System.out.println("$animals - Empty? -- ${animals.isEmpty()}")
animals.enqueue("Zebra")
System.out.println("$animals - Empty? -- ${animals.isEmpty()}")
animals.dequeue()
System.out.println("$animals - Empty? -- ${animals.isEmpty()}")
println()
val languages = Queue(arrayOf("Kotlin", "Java"))
println("$languages - Empty? -- ${languages.isEmpty()}")
languages.enqueue("C")
println("$languages - Empty? -- ${languages.isEmpty()}")
languages.dequeue()
println("$languages - Empty? -- ${languages.isEmpty()}")
languages.dequeue()
println("$languages - Empty? -- ${languages.isEmpty()}")
languages.dequeue()
println("$languages - Empty? -- ${languages.isEmpty()}")
// testQueueOf
val languages1 = queueOf("Kotlin", "Java")
println(languages1)
languages1.enqueue("C")
println(languages1)
languages1.dequeue()
println(languages1)
}
Output:
[] - Empty? -- true
[Lion] - Empty? -- false
[Lion, Tiger] - Empty? -- false
[Lion, Tiger, Crocodile, Cat, Dog, Cow, Cangaroo, Rat, Bull] - Empty? -- false
[Lion, Tiger, Crocodile, Cat, Dog, Cow, Cangaroo, Rat, Bull, Ox] - Empty? -- false
[Lion, Tiger, Crocodile, Cat, Dog, Cow, Cangaroo, Rat, Bull, Ox, Zebra] - Empty? -- false
[Tiger, Crocodile, Cat, Dog, Cow, Cangaroo, Rat, Bull, Ox, Zebra] - Empty? -- false
[Kotlin, Java] - Empty? -- false
[Kotlin, Java, C] - Empty? -- false
[Java, C] - Empty? -- false
[C] - Empty? -- false
[] - Empty? -- true
[Kotlin, Java]
[Kotlin, Java, C]
[Java, C]Related Data Structures and Algorithms in Kotlin
- Stack Data Structure Implementation in Kotlin
- Queue Data Structure Implementation in Kotlin
- Deque Implementation in Kotlin
- Singly Linked List Implementation in Kotlin
- Doubly Linked List Implementation in Kotlin
- Circular Linked List Implementation in Kotlin
- Bubble Sort Algorithm in Kotlin
- Heap Sort Algorithm in Kotlin
- Insertion Sort Algorithm in Kotlin
- Merge Sort Algorithm in Kotlin
- Quick Sort Algorithm in Kotlin
- Selection Sort Algorithm in Kotlin
- Stack Data Structure Implementation in Kotlin
- Queue Data Structure Implementation in Kotlin
- Deque Implementation in Kotlin
- Singly Linked List Implementation in Kotlin
- Doubly Linked List Implementation in Kotlin
- Circular Linked List Implementation in Kotlin
- Bubble Sort Algorithm in Kotlin
- Heap Sort Algorithm in Kotlin
- Insertion Sort Algorithm in Kotlin
- Merge Sort Algorithm in Kotlin
- Quick Sort Algorithm in Kotlin
- Selection Sort Algorithm in Kotlin
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
🆕 High-Demand
80–90% OFF
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
🆕 High-Demand
80–90% OFF
ChatGPT + Generative AI + Prompt Engineering for Beginners
🚀 Trending Now
80–90% OFF
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
🌟 Top Rated
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
🌟 Top Rated
80–90% OFF
Testing Spring Boot Application with JUnit and Mockito
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Master Spring Data JPA with Hibernate
🔥 Bestseller
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
🎓 Student Favorite
80–90% OFF
Available in Udemy for Business
Available in Udemy for Business
Comments
Post a Comment
Leave Comment