Skip to main content

How to merge two LinkedLists in Kotlin

How to merge two LinkedLists in Kotlin.

Here's a step-by-step tutorial on how to merge two LinkedLists in Kotlin:

Step 1: Create a Node class

In Kotlin, we'll start by creating a Node class that represents a single node in our LinkedList. Each node will have a value and a reference to the next node.

class Node(var value: Int, var next: Node? = null)

Step 2: Create a LinkedList class

Next, let's create a LinkedList class that will hold our Nodes. This class will have a reference to the head of the LinkedList and will provide methods for adding nodes to the list.

class LinkedList {
var head: Node? = null

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

Step 3: Create a mergeLists function

Now, let's create a function called mergeLists that takes in two LinkedLists as parameters and returns a new merged LinkedList. This function will iterate through both lists, comparing the values of the nodes and merging them into a new list.

fun mergeLists(list1: LinkedList, list2: LinkedList): LinkedList {
val mergedList = LinkedList()
var currentNode1 = list1.head
var currentNode2 = list2.head

while (currentNode1 != null && currentNode2 != null) {
if (currentNode1.value <= currentNode2.value) {
mergedList.add(currentNode1.value)
currentNode1 = currentNode1.next
} else {
mergedList.add(currentNode2.value)
currentNode2 = currentNode2.next
}
}

while (currentNode1 != null) {
mergedList.add(currentNode1.value)
currentNode1 = currentNode1.next
}

while (currentNode2 != null) {
mergedList.add(currentNode2.value)
currentNode2 = currentNode2.next
}

return mergedList
}

Step 4: Test the mergeLists function

Finally, let's create two LinkedLists, add some nodes to them, and merge them using the mergeLists function.

fun main() {
val list1 = LinkedList()
list1.add(1)
list1.add(3)
list1.add(5)

val list2 = LinkedList()
list2.add(2)
list2.add(4)
list2.add(6)

val mergedList = mergeLists(list1, list2)

var currentNode = mergedList.head
while (currentNode != null) {
println(currentNode.value)
currentNode = currentNode.next
}
}

This will output:

1
2
3
4
5
6

And that's it! You've successfully merged two LinkedLists in Kotlin. Feel free to modify the code as needed for your specific use case.