Sobes.tech
Junior — Middle

Can you list the main operations performed by a stack data structure?

sobes.tech AI

Answer from AI

Main stack operations:

  • push — add an element to the top of the stack.
  • pop — remove and return the top element.
  • peek (or top) — view the top element without removing it.
  • isEmpty — check if the stack is empty.

The stack operates on the LIFO (Last In, First Out) principle, meaning the last added element will be the first to be retrieved.

Example in Kotlin for Android:

val stack = ArrayDeque<Int>()
stack.push(1) // add 1
stack.push(2) // add 2
println(stack.peek()) // 2
println(stack.pop())  // 2
println(stack.pop())  // 1