diff --git a/src/main/kotlin/data_structures/linked_list/LinkedList.kt b/src/main/kotlin/data_structures/linked_list/LinkedList.kt index f1df7c6..aad9c2a 100644 --- a/src/main/kotlin/data_structures/linked_list/LinkedList.kt +++ b/src/main/kotlin/data_structures/linked_list/LinkedList.kt @@ -199,3 +199,14 @@ class LinkedList : Iterable> { return NodeIterator(this) } } + +/** + * Converts the Linked List to an array. + */ +inline fun LinkedList.toArray(): Array { + val newArray = arrayOfNulls(this.size()) + this.forEachIndexed { i, node -> + newArray[i] = node.value + } + return newArray +} diff --git a/src/test/kotlin/data_structures/linked_list/LinkedListTest.kt b/src/test/kotlin/data_structures/linked_list/LinkedListTest.kt index fdf4f35..5f0d0f1 100644 --- a/src/test/kotlin/data_structures/linked_list/LinkedListTest.kt +++ b/src/test/kotlin/data_structures/linked_list/LinkedListTest.kt @@ -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() + linkedList.append("First") + linkedList.append("Second") + + // Test + val result = linkedList.toArray() + + // Assert + assertContentEquals(arrayOf("First", "Second"), result) + } } \ No newline at end of file