Stacks

A stack is a linear list in which all insertion and deletion operations (and, typically, data access operations) are performed only at one end of the list.

This type of structure defines a set of rules:

A stack is a simple data structure, convenient for many operations requiring ordering or forced execution. The space complexity for n push operations is O(n), while the average case is O(1). Similarly, pop and peek have O(1) complexity, as do isEmpty and isFull.

Stack Definition

Code:

enum Stack[+A]:
  case EmptyStack
  case NonEmptyStack(value: A, tail: Stack[A])

val emptyStack: Stack[Int]    = EmptyStack
val nonEmptyStack: Stack[Int] = NonEmptyStack(2, NonEmptyStack(1, EmptyStack))

Head element

Complexity:

Code:

enum Stack[+A]:
  lazy val headOption: Option[A] = this match
    case EmptyStack          => None
    case NonEmptyStack(h, _) => Some(h) 

emptyStack.headOption         // None
nonEmptyStack.headOption      // Some(2)

Tail of the stack without the head element

Complexity:

Code:

enum Stack[+A]:
  lazy val tailOption: Option[Stack[A]] = this match
    case EmptyStack             => None
    case NonEmptyStack(_, tail) => Some(tail)

emptyStack.tailOption         // None
nonEmptyStack.tailOption      // Some(NonEmptyStack(1,EmptyStack))

Check if the stack is empty

Complexity:

Code:

enum Stack[+A]:
  lazy val isEmpty: Boolean = this match
    case EmptyStack          => true
    case NonEmptyStack(_, _) => false

emptyStack.isEmpty            // true
nonEmptyStack.isEmpty         // false

Computing the length of the stack

Complexity:

Code:

enum Stack[+A]:
  lazy val length: Int = this match
    case EmptyStack             => 0
    case NonEmptyStack(_, tail) => 1 + tail.length

emptyStack.length             // 0
nonEmptyStack.length          // 2

Push element onto stack

Complexity:

Code:

enum Stack[+A]:
  def push[B >: A](value: B): Stack[B] = NonEmptyStack(value, this)

emptyStack.push(5)            
// NonEmptyStack(5,EmptyStack)
nonEmptyStack.push(5)
// NonEmptyStack(5,NonEmptyStack(2,NonEmptyStack(1,EmptyStack)))

Pop element from stack

Complexity:

Code:

enum Stack[+A]:
  def pop(): Option[(A, Stack[A])] = this match
    case EmptyStack                 => None
    case NonEmptyStack(value, tail) => Some((value, tail))

emptyStack.pop()
// None
nonEmptyStack.pop()
// Some((2,NonEmptyStack(1,EmptyStack)))

Peek element from stack

Complexity:

Code:

enum Stack[+A]:
  def peek(): Option[(A, Stack[A])] = this match
    case EmptyStack              => None
    case NonEmptyStack(value, _) => Some((value, this))

emptyStack.peek()
// None
nonEmptyStack.peek()
// Some((2,NonEmptyStack(2,NonEmptyStack(1,EmptyStack))))

Links: