Skip to main content

How to clone a LinkedList in Kotlin

How to clone a LinkedList in Kotlin.

Here's a step-by-step tutorial on how to clone a LinkedList in Kotlin:

  1. First, let's create a class for our LinkedList node. This class will have a value and a reference to the next node in the list:
class Node<T>(val value: T, var next: Node<T>? = null)
  1. Next, let's create a LinkedList class that will contain our nodes. This class will have methods to add nodes to the list, print the list, and clone the list:
class LinkedList<T> {
private var head: Node<T>? = null

fun add(value: T) {
val newNode = Node(value)
if (head == null) {
head = newNode
} else {
var current = head
while (current?.next != null) {
current = current.next
}
current?.next = newNode
}
}

fun printList() {
var current = head
while (current != null) {
print("${current.value} ")
current = current.next
}
println()
}

fun clone(): LinkedList<T> {
val newList = LinkedList<T>()
var current = head
while (current != null) {
newList.add(current.value)
current = current.next
}
return newList
}
}
  1. Let's test our LinkedList class by adding some nodes and printing the list:
fun main() {
val list = LinkedList<Int>()
list.add(1)
list.add(2)
list.add(3)
list.printList()
}
  1. Now, let's clone the LinkedList and print the cloned list:
fun main() {
val list = LinkedList<Int>()
list.add(1)
list.add(2)
list.add(3)
val clonedList = list.clone()
clonedList.printList()
}
  1. Finally, let's run our main function and see the output:
1 2 3
1 2 3

Congratulations! You have successfully cloned a LinkedList in Kotlin. The clone method creates a new LinkedList object and iterates through the original list, adding each value to the new list. This ensures that the cloned list is a separate copy of the original list.