Stacks Implementation In Kotlin -Data Structure And Algorithms

·

2 min read

Stack is an abstract data type with a bounded(predefined) capacity. It is a simple data structure that allows adding and removing elements in a particular order. Every time an element is added, it goes on the top of the stack and the only element that can be removed is the element that is at the top of the stack, just like a pile of objects.

stack.png

Usage :)

  • Implement the undo feature.
  • Build compliers (eg syntax checking)

  • Evaluate Expressions, eg (1 + 2*3)

  • Build Navigation (eg forward/back)

Operations :D

  • push() -> Adds an item in the stack. If the stack is full, it is said to be an Overflow condition

  • pop() -> Removes and item from the stack. The items are popped in the reversed order in which they are pushed. If the stack is empty, then it is said to be and Underflow condition.

  • peek() or top() -> Returns the top element of the stack.

  • isEmpty() -> Returns true if the stack is empty, else false.

class MyStack {

    private var items = Array<Int>(5) { 0 }
    var count = 0  /** contains the size of the stack **/

    fun push(item: Int) {
        if (count == items.size) {
            throw StackOverflowError()
        }
        items[count++] = item
    }

    fun pop(): Int {
        if (count == 0) {
            throw IllegalAccessException()
        }
        return items[--count]
    }

    fun peek(): Int = items[count]

    fun isEmpty() = count == 0

    override fun toString(): String {
        val array = items.copyOfRange(0, count)
        return array.contentToString()
    }

}

fun main() {
    val stack: MyStack = MyStack()
    stack.push(1)
    stack.push(2)
    println(stack)
    stack.pop()
    println(stack.peek())

}

Analysis :D

  • Push Operations O(1)

  • Pop Operations O(1)

  • Pop Operations O(1)

  • Search Operation O(n)