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
ListNode
calleddummy
with a value of-1
. This node will act as the head of the merged linked list. - Initialize two pointers
p1
andp2
to the heads of the input linked listsl1
andl2
. - Iterate through both linked lists as long as both pointers
p1
andp2
are not null. At each iteration, compare the values ofp1
andp2
. Ifp1.val
is less thanp2.val
, appendp1
to the merged linked list by settingcurrent.next
top1
and advancingp1
to its next node. Otherwise, appendp2
to the merged linked list by settingcurrent.next
top2
and advancingp2
to its next node. Finally, advancecurrent
to its next node. - If one of the input linked lists (
l1
orl2
) 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
next
node of thedummy
node 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