| 34 | } |
| 35 | |
| 36 | fun 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 | } |