Queue Implementation In Kotlin -Data Structure And Algorithms

·

2 min read

Queue are data structure that follows the FIRST IN, FIRST OUT (FIFO), ie the first element that is added to the queue is the first one to be removed. Elements are always added to the back and removed from the front. Think of it as a line of people, waiting for a bus. The person who is at the beginning of the line is the first one to enter the bus.

queue.png

Operations :)

  • enqueue() : is the operation for adding an element into Queue.
  • dequeue() : is the operation for removing an element from Queue.

Queue Implementation Through Arrays :D

class MyQueue(val size: Int = 5) {

    private var items = Array<Int>(size) { 0 }
    private var FRONT = 0
    private var REAR = 0
    private var count = 0

    fun enqueue(item: Int) {
        if (count == items.size) throw IllegalAccessException()
        items[REAR] = item
        REAR = (REAR + 1) % items.size  // for circular arrayy.
        count++
    }

    fun dequeue(): Int {
        if (isEmpty()) throw IllegalAccessException("Queue is empty..")
        val frontItem = items[FRONT]
        items[FRONT] = 0
        FRONT = (FRONT + 1) % items.size
        count--
        return frontItem
    }

    fun isEmpty(): Boolean = count == 0

    override fun toString(): String {
//        val array = items.copyOfRange(FRONT, REAR)
        return items.contentToString()
    }

}

fun main() {
    val myQueue = MyQueue()
    myQueue.enqueue(3)
    myQueue.enqueue(4)
    myQueue.enqueue(5)
    myQueue.enqueue(6)
    println(myQueue)
    myQueue.dequeue()
    println(myQueue)
    myQueue.enqueue(6)
    println(myQueue)

}

Queue Implementation Through Stack :D


class StackQueue {
    private val stack = Stack<Int>()
    private val secondStack = Stack<Int>()

    fun enqueue(item: Int) {
        stack.push(item)
    }

    fun dequeue(): Int {
        if (stack.isEmpty() && secondStack.isEmpty())
            throw IllegalStateException()

        while (!stack.isEmpty()) {
            secondStack.push(stack.pop())
        }
        return secondStack.pop()
    }
}