Stack Implementation in Scala

1. Introduction

A Stack is a linear data structure that follows the Last In First Out (LIFO) principle. This means that the last element added to the stack will be the first element to be removed. Conceptually, it can be compared to a stack of plates; the plate added most recently is the first to be used. In computing, stacks are used in various algorithms, function calls, and many other processes.

2. Implementation Steps

1. Use Scala's built-in mutable.Stack for the base structure.

2. Implement the push method to add an element to the top of the stack.

3. Implement the pop method to remove and return the top element of the stack.

4. Implement a peek method to view the top element without removing it.

5. Write the client code to test the Stack implementation.

3. Implementation in Scala

import scala.collection.mutable
class Stack[A] {
  private val stack = new mutable.Stack[A]
  // Add an element to the top of the stack
  def push(element: A): Unit = {
    stack.push(element)
  }
  // Remove and return the top element of the stack
  def pop(): Option[A] = {
    if(stack.isEmpty) None else Some(stack.pop())
  }
  // View the top element without removing it
  def peek(): Option[A] = {
    if(stack.isEmpty) None else Some(stack.top)
  }
}

Client Code:

val s = new Stack[Int]
s.push(10)
s.push(20)
s.push(30)
println(s.peek())    // Expected: Some(30)
println(s.pop())     // Expected: Some(30)
println(s.peek())    // Expected: Some(20)

Output:

Some(30)
Some(30)
Some(20)

Explanation:

1. import scala.collection.mutable: This line imports Scala's mutable collections, which include the built-in Stack.

2. class Stack[A]: This defines our generic Stack class.

3. stack = new mutable.Stack[A]: Initializes the underlying stack structure.

4. push(element: A): This method is responsible for adding an element to the top of the stack.

5. pop(): This method removes and returns the top element of the stack. If the stack is empty, it returns None.

6. peek(): A method to fetch the top element without removing it. Returns None if the stack is empty.

The implemented Stack is a basic representation and leverages Scala's built-in Stack to handle the underlying operations efficiently.


Comments