21. Merge Two Sorted Lists

  • Source : Link
  • Author : Han
  • Date : 2022-02-14

Problems

You are given the heads of two sorted linked lists list1 and list2.

Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.

Return the head of the merged linked list.

Example 1:

https://assets.leetcode.com/uploads/2020/10/03/merge_ex1.jpg

1
2
3
Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]

Example 2:

1
2
3
Input: list1 = [], list2 = []
Output: []

Example 3:

1
2
3
Input: list1 = [], list2 = [0]
Output: [0]

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
 * Example:
 * var li = ListNode(5)
 * var v = li.`val`
 * Definition for singly-linked list.
 * class ListNode(var `val`: Int) {
 *     var next: ListNode? = null
 * }
 */
class Solution {
    fun mergeTwoLists(list1: ListNode?, list2: ListNode?): ListNode? {
        return when {
            list1 == null && list2 == null -> null
            list1 == null -> list2
            list2 == null -> list1
            list1.`val` < list2.`val` -> {
                list1.next = mergeTwoLists(list1.next, list2)
                list1
            }
            else -> {
                list2.next = mergeTwoLists(list2.next, list1)
                list2
            }
        }
    }
}