LinkedList: implement emptyList and listOf
This commit is contained in:
parent
8ec2b4f2fe
commit
25a47d62d6
2 changed files with 40 additions and 0 deletions
|
@ -198,6 +198,8 @@ class LinkedList<T> : Iterable<Node<T>> {
|
||||||
override fun iterator(): Iterator<Node<T>> {
|
override fun iterator(): Iterator<Node<T>> {
|
||||||
return NodeIterator(this)
|
return NodeIterator(this)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
companion object
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -210,3 +212,22 @@ inline fun <reified E> LinkedList<E>.toArray(): Array<E?> {
|
||||||
}
|
}
|
||||||
return newArray
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
|
|
@ -1,6 +1,8 @@
|
||||||
package data_structures.linked_list
|
package data_structures.linked_list
|
||||||
|
|
||||||
import dev.nuculabs.dsa.data_structures.linked_list.LinkedList
|
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 dev.nuculabs.dsa.data_structures.linked_list.toArray
|
||||||
import org.junit.jupiter.api.Test
|
import org.junit.jupiter.api.Test
|
||||||
|
|
||||||
|
@ -289,4 +291,21 @@ class LinkedListTest {
|
||||||
// Assert
|
// Assert
|
||||||
assertContentEquals(arrayOf("First", "Second"), result)
|
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())
|
||||||
|
}
|
||||||
}
|
}
|
Loading…
Reference in a new issue