MCPcopy Create free account
hub / github.com/ByteByteGoHq/coding-interview-patterns / merge

Function merge

kotlin/Sort and Search/SortLinkedList.kt:36–60  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

34}
35
36fun merge(l1: ListNode?, l2: ListNode?): ListNode? {
37 val dummy = ListNode()
38 // This pointer will be used to append nodes to the tail of the
39 // merged linked list.
40 var tail = dummy
41 var list1 = l1
42 var list2 = l2
43 // Continually append the node with the smaller value from each
44 // linked list to the merged linked list until one of the linked
45 // lists has no more nodes to merge.
46 while (list1 != null && list2 != null) {
47 if (list1.value < list2.value) {
48 tail.next = list1
49 list1 = list1.next
50 } else {
51 tail.next = list2
52 list2 = list2.next
53 }
54 tail = tail.next!!
55 }
56 // One of the two linked lists could still have nodes remaining.
57 // Attach those nodes to the end of the merged linked list.
58 tail.next = list1 ?: list2
59 return dummy.next
60}

Callers 1

sortLinkedListFunction · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected