-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmerge-two-sorted-lists.go
46 lines (36 loc) · 1018 Bytes
/
merge-two-sorted-lists.go
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package main
import (
"fmt"
. "github.com/dimaglushkov/solutions/ADS/list"
)
// source: https://leetcode.com/problems/merge-two-sorted-lists/
func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode {
if list1 == nil {
return list2
}
if list2 == nil {
return list1
}
if list1.Val <= list2.Val {
list1.Next = mergeTwoLists(list1.Next, list2)
return list1
} else {
list2.Next = mergeTwoLists(list1, list2.Next)
return list2
}
}
func main() {
// Example 1
var list11 *ListNode = NewList([]int{1, 2, 4})
var list21 *ListNode = NewList([]int{1, 3, 4})
var res1 = mergeTwoLists(list11, list21)
fmt.Println("Expected: [1,1,2,3,4,4] Output: ", res1)
// Example 2
var list12 *ListNode = NewList([]int{})
var list22 *ListNode = NewList([]int{})
fmt.Println("Expected: [] Output: ", mergeTwoLists(list12, list22))
// Example 3
var list13 *ListNode = NewList([]int{})
var list23 *ListNode = NewList([]int{0})
fmt.Println("Expected: [0] Output: ", mergeTwoLists(list13, list23))
}