LinkedList: implement emptyList and listOf

This commit is contained in:
Denis-Cosmin Nutiu 2024-04-14 11:28:30 +03:00
parent 8ec2b4f2fe
commit 25a47d62d6
2 changed files with 40 additions and 0 deletions

View file

@ -198,6 +198,8 @@ class LinkedList<T> : Iterable<Node<T>> {
override fun iterator(): Iterator<Node<T>> {
return NodeIterator(this)
}
companion object
}
/**
@ -210,3 +212,22 @@ inline fun <reified E> LinkedList<E>.toArray(): Array<E?> {
}
return newArray
}
/**
* Creates an empty linked list.
*/
fun <T> LinkedList.Companion.emptyList(): LinkedList<T> {
return LinkedList()
}
/**
* Constructs a linked list from a variable number of arguments.
*/
fun <T> LinkedList.Companion.listOf(vararg items: T): LinkedList<T> {
val linkedList = LinkedList<T>()
items.forEach {
linkedList.append(it)
}
return linkedList
}

View file

@ -1,6 +1,8 @@
package data_structures.linked_list
import dev.nuculabs.dsa.data_structures.linked_list.LinkedList
import dev.nuculabs.dsa.data_structures.linked_list.emptyList
import dev.nuculabs.dsa.data_structures.linked_list.listOf
import dev.nuculabs.dsa.data_structures.linked_list.toArray
import org.junit.jupiter.api.Test
@ -289,4 +291,21 @@ class LinkedListTest {
// Assert
assertContentEquals(arrayOf("First", "Second"), result)
}
@Test
fun emptyList() {
// Test
val list = LinkedList.emptyList<String>()
// Assert
assertEquals(0, list.size())
}
@Test
fun listOf() {
// Test
val list = LinkedList.listOf("One", "Two", "Three")
// Assert
assertEquals(3, list.size())
assertContentEquals(listOf("One", "Two", "Three"), list.toJavaList())
}
}