How to use stack in Scala

1 Answer

0 votes
import scala.collection.mutable.Stack

object StackExample extends App {
  val stack = Stack[String]()

  // Push elements onto the stack
  stack.push("Scala")
  stack.push("C")
  stack.push("C++")
  stack.push("Java")
  stack.push("Python")

  // Print the full stack
  println("Full stack (top to bottom):")
  stack.foreach(println)
  println()

  // Peek at the top element
  println(s"Top of stack: ${stack.top}\n")

  // Pop elements off the stack
  println("Popping elements:")
  while (stack.nonEmpty) {
    println(stack.pop())
  }
  println()

  // Print the full stack
  println("Full stack (top to bottom):")
  stack.foreach(println)
}



 
/*
run:
  
Full stack (top to bottom):
Python
Java
C++
C
Scala

Top of stack: Python

Popping elements:
Python
Java
C++
C
Scala

Full stack (top to bottom):
  
*/

 

 



answered Aug 15, 2025 by avibootz
edited Aug 15, 2025 by avibootz

Related questions

...