tasks a-s
This commit is contained in:
parent
47bf37c096
commit
b83f433714
12433 changed files with 156208 additions and 123 deletions
34
Task/Queue-Definition/Scala/queue-definition-1.scala
Normal file
34
Task/Queue-Definition/Scala/queue-definition-1.scala
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
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(", ", ", ")")
|
||||
}
|
||||
11
Task/Queue-Definition/Scala/queue-definition-2.scala
Normal file
11
Task/Queue-Definition/Scala/queue-definition-2.scala
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
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)
|
||||
Loading…
Add table
Add a link
Reference in a new issue