LinkedList: move toArray() as an extension method
This commit is contained in:
parent
e43fc8e7f0
commit
8ec2b4f2fe
2 changed files with 26 additions and 0 deletions
|
@ -199,3 +199,14 @@ class LinkedList<T> : Iterable<Node<T>> {
|
|||
return NodeIterator(this)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the Linked List to an array.
|
||||
*/
|
||||
inline fun <reified E> LinkedList<E>.toArray(): Array<E?> {
|
||||
val newArray = arrayOfNulls<E>(this.size())
|
||||
this.forEachIndexed { i, node ->
|
||||
newArray[i] = node.value
|
||||
}
|
||||
return newArray
|
||||
}
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
package data_structures.linked_list
|
||||
|
||||
import dev.nuculabs.dsa.data_structures.linked_list.LinkedList
|
||||
import dev.nuculabs.dsa.data_structures.linked_list.toArray
|
||||
import org.junit.jupiter.api.Test
|
||||
|
||||
import org.junit.jupiter.api.Assertions.*
|
||||
|
@ -274,4 +275,18 @@ class LinkedListTest {
|
|||
assertEquals("Fifth", linkedList.getFirst())
|
||||
assertEquals("First", linkedList.getLast())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun toArray() {
|
||||
// Setup
|
||||
val linkedList = LinkedList<String>()
|
||||
linkedList.append("First")
|
||||
linkedList.append("Second")
|
||||
|
||||
// Test
|
||||
val result = linkedList.toArray()
|
||||
|
||||
// Assert
|
||||
assertContentEquals(arrayOf("First", "Second"), result)
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue