30% Therapy – 40% Practice – 30% Work project

Scala Collections – Stack



Stack is Last In First Out, LIFO data structure and allows to insert and retrieve element at top, in LIFO manner.

Declaring Stack Variables

The following is the syntax for declaring an Stack variable.

Syntax

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 −

Command

stack.push(6)

Value can be retrived from top by using commands like the following −

Command

stack.top

Value can be removed from top by using commands like the following −

Command

stack.pop

Processing Stack

Below is an example program of showing how to create, initialize and process Stack −

Example

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.

Command

>scalac Demo.scala
>scala Demo

Output

Top Element: 2
Removed Element: 2
Top Element: 1
Translate »