Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,844 questions

51,765 answers

573 users

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

...