11.28. Using a Stack
Problem
You want to use a stack data structure in a Scala application.
Solution
A stack is a last-in, first-out (LIFO) data structure. In most
programming languages you add elements to a stack using a push method, and take elements off the stack
with pop, and Scala is no
different.
Scala has both immutable and mutable versions of a stack, as well
as an ArrayStack (discussed shortly).
The following examples demonstrate how to use the
mutable Stack
class.
Create an empty, mutable stack of any data type:
importscala.collection.mutable.Stackvarints=Stack[Int]()varfruits=Stack[String]()caseclassPerson(varname:String)varpeople=Stack[Person]()
You can also populate a stack with initial elements when you create it:
valints=Stack(1,2,3)
Once you have a mutable stack, push elements onto the stack with
push:
// create a stack scala>var fruits = Stack[String]()fruits: scala.collection.mutable.Stack[String] = Stack() // add one element at a time scala>fruits.push("apple")res0: scala.collection.mutable.Stack[String] = Stack(apple) scala>fruits.push("banana")res1: scala.collection.mutable.Stack[String] = Stack(banana, apple) // add multiple elements scala>fruits.push("coconut", "orange", "pineapple")res2: scala.collection.mutable.Stack[String] = Stack(pineapple, orange, coconut, banana, apple)
To take elements off the stack, pop them off the top of the stack:
scala>val next = fruits.popnext: String = pineapple scala>fruitsres3: scala.collection.mutable.Stack[String] ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access