
Stack is Last In First Out, LIFO data structure and allows to insert and retrieve element at top, in LIFO manner.
The following is the syntax for declaring an Stack variable.
val stack = Stack(1, 2, 3, 4, 5)
Here, stack is declared as an Stack of numbers. Value can be added at top by using commands like the following −
stack.push(6)
Value can be retrived from top by using commands like the following −
stack.top
Value can be removed from top by using commands like the following −
stack.pop
Below is an example program of showing how to create, initialize and process Stack −
import scala.collection.mutable.Stack
object Demo {
def main(args: Array[String]) = {
var stack: Stack[Int] = Stack();
// Add elements
stack.push(1);
stack.push(2);
// Print element at top
println("Top Element: " + stack.top)
// Print element
println("Removed Element: " + stack.pop())
// Print element
println("Top Element: " + stack.top)
}
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala \>scala Demo
Top Element: 2 Removed Element: 2 Top Element: 1