Skip to content

Instantly share code, notes, and snippets.

@RaccoonDev
Created February 26, 2020 15:08
Show Gist options
  • Save RaccoonDev/6114c332f1afa699096511979acc9ed5 to your computer and use it in GitHub Desktop.
Save RaccoonDev/6114c332f1afa699096511979acc9ed5 to your computer and use it in GitHub Desktop.
Simple linked list with tail addition
package excercises
abstract class MyList {
def head(): Int
def tail(): MyList
def isEmpty: Boolean
def add(element: Int): MyList
def printElements: String
override def toString: String = "[" + printElements + "]"
}
object Empty extends MyList {
override def head(): Int = throw new NoSuchElementException
override def tail(): MyList = throw new NoSuchElementException
override def isEmpty: Boolean = true
override def add(element: Int): MyList = new Cons(element, Empty)
override def printElements: String = ""
}
class Cons(head: Int, tail: MyList) extends MyList {
override def head(): Int = head
override def tail(): MyList = tail
override def isEmpty: Boolean = false
override def add(element: Int): MyList =
if(tail.isEmpty) new Cons(head, new Cons(element, tail))
else new Cons(head, tail.add(element))
override def printElements: String =
if(tail.isEmpty) "" + head
else head + " " + tail.printElements
}
object CreatingLinkedList extends App {
val list = new Cons(1, Empty)
println(list.toString)
val listTwo = list.add(2).add(3).add(4)
println(listTwo.toString)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment