How to resolve the algorithm Queue/Definition step by step in the Scala programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Queue/Definition step by step in the Scala programming language
Table of Contents
Problem Statement
Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion.
Operations:
Errors:
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Queue/Definition step by step in the Scala programming language
Source code in the scala programming language
class Queue[T] {
private[this] class Node[T](val value:T) {
var next:Option[Node[T]]=None
def append(n:Node[T])=next=Some(n)
}
private[this] var head:Option[Node[T]]=None
private[this] var tail:Option[Node[T]]=None
def isEmpty=head.isEmpty
def enqueue(item:T)={
val n=new Node(item)
if(isEmpty) head=Some(n) else tail.get.append(n)
tail=Some(n)
}
def dequeue:T=head match {
case Some(item) => head=item.next; item.value
case None => throw new java.util.NoSuchElementException()
}
def front:T=head match {
case Some(item) => item.value
case None => throw new java.util.NoSuchElementException()
}
def iterator: Iterator[T]=new Iterator[T]{
private[this] var it=head;
override def hasNext=it.isDefined
override def next:T={val n=it.get; it=n.next; n.value}
}
override def toString()=iterator.mkString("Queue(", ", ", ")")
}
val q=new Queue[Int]()
println("isEmpty = " + q.isEmpty)
try{q dequeue} catch{case _:java.util.NoSuchElementException => println("dequeue(empty) failed.")}
q enqueue 1
q enqueue 2
q enqueue 3
println("queue = " + q)
println("front = " + q.front)
println("dequeue = " + q.dequeue)
println("dequeue = " + q.dequeue)
println("isEmpty = " + q.isEmpty)
You may also check:How to resolve the algorithm Function composition step by step in the Rust programming language
You may also check:How to resolve the algorithm Rosetta Code/Count examples step by step in the Racket programming language
You may also check:How to resolve the algorithm Higher-order functions step by step in the Sparkling programming language
You may also check:How to resolve the algorithm Left factorials step by step in the Go programming language
You may also check:How to resolve the algorithm Execute a system command step by step in the AWK programming language