Created
July 15, 2023 04:12
-
-
Save ahmedhosnypro/2dbcf0d4f7c857ab2ac325e3e03313b9 to your computer and use it in GitHub Desktop.
Kotlin CircularQueue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Suppress("UNCHECKED_CAST") | |
class CircularQueue<T>( | |
private val capacity: Int, | |
) { | |
private val elements: Array<T?> = arrayOfNulls<Any?>(capacity) as Array<T?> | |
private var front = 0 | |
private var rear = 0 | |
private var count = 0 | |
private val isEmpty: Boolean | |
get() = count == 0 | |
private val isFull: Boolean | |
get() = count == capacity | |
fun enqueue(element: T?): Boolean { | |
if (isFull) { | |
return false | |
} | |
elements[rear] = element | |
rear = (rear + 1) % capacity | |
count++ | |
return true | |
} | |
fun dequeue(): T? { | |
if (isEmpty) { | |
return null | |
} | |
val element: T? = elements[front] | |
elements[front] = null | |
front = (front + 1) % capacity | |
count-- | |
return element | |
} | |
fun size(): Int { | |
return count | |
} | |
fun capacity(): Int { | |
return capacity | |
} | |
private fun toArray(): Array<T?> { | |
if (isEmpty) { | |
return arrayOfNulls<Any?>(0) as Array<T?> | |
} | |
val array: Array<T?> = arrayOfNulls<Any?>(count) as Array<T?> | |
var index = 0 | |
for (i in front until front + count) { | |
array[index++] = elements[i % capacity] | |
} | |
return array | |
} | |
override fun toString(): String { | |
if (isEmpty) { | |
return "" | |
} | |
val sb = StringBuilder() | |
val arr = toArray() | |
for (i in arr.indices) { | |
sb.append(arr[i]) | |
if (i != capacity - 1) { | |
sb.append("\n") | |
} | |
} | |
return sb.toString() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment