Know stack and basic operation using Kotlin
Introduction:
1 — It is a Linear Data Structure.
2 — Follows a specific order to perform operations like insertion, deletion.
3 — Order is known as LIFO means last in first out.
Get Dinesh Kumar’s stories in your inbox
Join Medium for free to get updates from this writer.
In computer memory data is arranged like that when we insert any new data in stack data structure, it will follow like a pile of plates.
Basic operations are — push(), pop(), isEmpty(), peek()
Creation of stack data structure:
class MyStack(private val capacity: Int) {
private val stackArray = arrayOfNulls<Int>(capacity) // Fixed-size array
private var top = -1 // Keeps track of the top element index
// Push (Add an element to the stack)
fun push(item: Int) {
if (top == capacity - 1) {
println("Stack Overflow! Cannot push $item.")
return
}
top++
stackArray[top] = item
println("Pushed: $item")
}
// Pop (Remove and return the top element)
fun pop(): Int? {
if (isEmpty()) {
println("Stack Underflow! Stack is empty.")
return null
}
val removedItem = stackArray[top]
stackArray[top] = null // Optional: Clear the reference
top--
println("Popped: $removedItem")
return removedItem
}
// Peek (See the top element without removing it)
fun peek(): Int? {
return if (isEmpty()) {
println("Stack is empty!")
null
} else {
stackArray[top]
}
}
// Check if the stack is empty
fun isEmpty(): Boolean {
return top == -1
}
// Get the size of the stack
fun size(): Int {
return top + 1
}
// Print the stack
fun printStack() {
if (isEmpty()) {
println("Stack is empty!")
return
}
print("Stack: ")
for (i in 0..top) {
print("${stackArray[i]} ")
}
println()
}
}
// Testing MyStack
fun main() {
val stack = MyStack(5) // Create a stack with a capacity of 5
stack.push(10)
stack.push(20)
stack.push(30)
stack.printStack() // Stack: 10 20 30
println("Peek: ${stack.peek()}") // Peek: 30
stack.pop() // Removes 30
stack.printStack() // Stack: 10 20
stack.pop() // Removes 20
stack.pop() // Removes 10
stack.pop() // Stack Underflow! Stack is empty.
}Pushed: 10
Pushed: 20
Pushed: 30
Stack: 10 20 30
Peek: 30
Popped: 30
Stack: 10 20
Popped: 20
Popped: 10
Stack Underflow! Stack is empty.
This is only basic points to know about stack.










