To merge two sorted linked lists, you can follow these steps:
- Initialize a new empty linked list.
- Set two pointers to the heads of the two input linked lists.
- Compare the values of the two nodes pointed by the two pointers. Append the smaller one to the new linked list and move the corresponding pointer to the next node.
- Repeat step 3 until one of the pointers reaches the end of the linked list.
- Append the rest of the nodes from the non-empty linked list to the new linked list.
- Return the head of the new linked list.
class ListNode(var `val`: Int) {
var next: ListNode? = null
}
fun mergeTwoLists(l1: ListNode?, l2: ListNode?): ListNode? {
// Step 1
val dummy = ListNode(-1)
var current: ListNode? = dummy
// Step 2
var p1 = l1
var p2 = l2
// Step 3
while (p1 != null && p2 != null) {
if (p1.`val` < p2.`val`) {
current?.next = p1
p1 = p1.next
} else {
current?.next = p2
p2 = p2.next
}
current = current?.next
}
// Step 4
if (p1 != null) {
current?.next = p1
} else {
current?.next = p2
}
// Step 5
return dummy.next
}- Create a new
ListNodecalleddummywith a value of-1. This node will act as the head of the merged linked list. - Initialize two pointers
p1andp2to the heads of the input linked listsl1andl2. - Iterate through both linked lists as long as both pointers
p1andp2are not null. At each iteration, compare the values ofp1andp2. Ifp1.valis less thanp2.val, appendp1to the merged linked list by settingcurrent.nexttop1and advancingp1to its next node. Otherwise, appendp2to the merged linked list by settingcurrent.nexttop2and advancingp2to its next node. Finally, advancecurrentto its next node. - If one of the input linked lists (
l1orl2) still has nodes remaining, append the rest of those nodes to the merged linked list. - Return the head of the merged linked list, which is the
nextnode of thedummynode we created in Step 1.
class ListNode(var `val`: Int) {
var next: ListNode? = null
}
fun mergeTwoLists(l1: ListNode?, l2: ListNode?): ListNode? {
// Step 1
val dummy = ListNode(-1)
var current: ListNode? = dummy
// Step 2
var p1 = l1
var p2 = l2
// Step 3
while (p1 != null && p2 != null) {
if (p1.`val` < p2.`val`) {
current?.next = p1
p1 = p1.next
} else {
current?.next = p2
p2 = p2.next
}
current = current?.next
}
// Step 4
if (p1 != null) {
current?.next = p1
} else {
current?.next = p2
}
// Step 5
return dummy.next
}
fun main() {
// Example usage
val l1 = ListNode(1).apply {
next = ListNode(3).apply {
next = ListNode(5)
}
}
val l2 = ListNode(2).apply {
next = ListNode(4).apply {
next = ListNode(6)
}
}
val mergedList = mergeTwoLists(l1, l2)
var current: ListNode? = mergedList
while (current != null) {
print("${current.`val`} ")
current = current.next
}
// Output: 1 2 3 4 5 6
}
In the main function, two example linked lists are created and passed to mergeTwoLists. The resulting merged linked list is printed to the console.
Output : 1 2 3 4 5 6