inf2kva/src/main/scala/ScalaGo/SimpleList.scala
2024-03-01 23:37:35 +01:00

60 lines
1.3 KiB
Scala

package ScalaGo
object SimpleList:
/**
* Implements a basic linked list.
*
* @param entry entry of the list element, 'None' if not provided
* @param next next element of the list, 'null' if not provided
* @tparam A type of the list's entries
*/
class SimpleList[A](var entry: Option[A] = None, var next: SimpleList[A] = null)
/**
* Append an item to the SimpleList
*
* @param list the list
* @param item append this item
*/
def append[A](list: SimpleList[A], item: A): Unit = {
var l = SimpleList(item, list)
return l
}
/**
* Determines the length of the SimpleList.
*
* @param list the list
* @return the length
*/
def length[A](list: SimpleList[A]): Int = {
var l = list
var counter: Int = 0
while l != null do {
counter = counter + 1
l = l.next
}
return counter
}
/**
* Tests if the SimpleList contains a given element.
*
* Tests for equality are done via '=='.
*
* @param list the list
* @param item search for this item
* @return true if the SimpleList contains the item, false if not
*/
def contains[A](list: SimpleList[A], item: A): Boolean = {
var l = list
while l != null do {
if (l.entry == item) then {
return true
}
l = l.next
}
return false
}