Stack in Kotlin : Add and Remove Operations

Home » Kotlin » Stack in Kotlin : Add and Remove Operations

Stack in Kotlin represents a linear data structure that operates on a Last In First Out (LIFO) basis. Linear and non-linear data structures organize and access data differently.

Linear structures, including arrays, queues, and linked lists, sequence data straightforwardly for easy traversal. In contrast, non-linear structures like trees and graphs enable intricate relationships among elements without a specific order.

A stack functions much like a stack of plates, where elements are added to and removed from the top. It involves two primary operations: pushing (adding) elements onto the stack and popping (removing) them.

stack in kotlin

Implementing a Stack in Kotlin

To create a Stack in Kotlin, we can use the built-in Stack class (from Java) or MutableList of Kotlin.

Using a MutableList (Adding an item – Push Operation)

 val stack = mutableListOf<Int>()
    
    stack.add(0)
    stack.add(10)
    stack.add(14)
    stack.add(11)

Removing the last item :

   stack.removeAt(stack.size - 1)

Or :

   stack.removeLast()

Program:

Open the Kotlin Playground and Write the following code :


fun main() {

    val stack = mutableListOf<Int>()
    
    stack.add(0)
    stack.add(10)
    stack.add(14)
    stack.add(11)
    
   stack.forEach {item -> print(" ["+ item + "]")} 
   
   // removing an item 
   stack.removeAt(stack.size - 1)
   
   println()
   println("After removing \n ---")
   
   stack.forEach {item -> print(" ["+ item + "]")} 
   
       
}

Output :

 [0] [10] [14] [11]
After removing 
 ---
 [0] [10] [14]

Using Stack (Java Class):

import java.util.Stack

fun main() {
    val stack = Stack<Int>()
    
    stack.push(0)
    stack.push(10)
    stack.push(14)
    stack.push(11)
    
    println("Stack: $stack")
    
    val removedElement = stack.pop()
    println("Popped/Removed element: $removedElement")
    
    println("Stack after popping: $stack")
}

Stack: [0, 10, 14, 11]
Popped/Removed element: 11
Stack after popping: [0, 10, 14]

Basic Operations on a Stack

Push Operation (Adding)

The push() function in a Stack adds elements to the top of the stack. In this example, stack.push(0) adds the element ‘0’ to the stack.

Pop operation (Removing)

Conversely, the pop() function removes and returns the top element from the Stack. In the example, val removedElement = stack.pop() removes the top element and assigns it to removedElement.

Using ArrayDeque : Removing first, last and middle element

import java.time.LocalTime
import java.time.format.DateTimeFormatter

fun main() {
   
      val stack = ArrayDeque<Int>()
      stack.addFirst(1)
      stack.add(4)
      stack.add(45)
      stack.add(34)
    
     update(stack)
     stack.removeFirst()
     update(stack)
     stack.removeLast()
     update(stack)
     
     stack.addAll(listOf(4,6,6,67,908,67))
     update(stack)
     
     // remove the middle element 
     val middleIndex = stack.size / 2
     stack.removeAt(middleIndex)
     update(stack)
   
  
}


fun update(stack: ArrayDeque<Int>)
{
   stack.forEach{
   item -> print("["+ item + "]")
   }
   println()
   println("--------")   
}


[1][4][45][34]
--------
[4][45][34]
--------
[4][45]
--------
[4][45][4][6][6][67][908][67]
--------
[4][45][4][6][67][908][67]

Let’s use ‘remove()‘ instead of ‘removeAt()‘ to eliminate the middle element.

 val middleIndexS = stack.size / 2
     val isEven = stack.size % 2 == 0
     val removeIndex = if(isEven) middleIndexS - 1 else middleIndexS
     val iterator = stack.iterator()
     var currentIndex = 0
     while(iterator.hasNext())
    {
        val item = iterator.next()
        if(currentIndex == removeIndex)
        {
            iterator.remove()
            break 
        }
        currentIndex++
    }

    update(stack)

The stack data structure is an essential tool for managing data in Last-In-First-Out manner. Stacks are really useful in programming. They help handle data and make algorithms smoother. Try using stacks in your Kotlin projects to see how they can make your code more efficient!

Stacks, a core linear structure, abide by a Last In First Out (LIFO) principle, enabling addition and removal of data from the top. This trait makes stacks adept at managing function calls, undo mechanisms, and parsing tasks in programming languages.

You may also like...