-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution21.go
More file actions
32 lines (29 loc) · 831 Bytes
/
solution21.go
File metadata and controls
32 lines (29 loc) · 831 Bytes
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
package solution21
// ============================================================================
// 21. Merge Two Sorted Lists
// URL: https://leetcode.com/problems/merge-two-sorted-lists/
// ============================================================================
type ListNode struct {
Val int
Next *ListNode
}
// mergeTwoLists merges two given lists into one
//
// This recursive approach is described here:
// https://www.geeksforgeeks.org/merge-two-sorted-linked-lists/
func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode {
var head *ListNode
if list1 == nil {
return list2
} else if list2 == nil {
return list1
}
if list1.Val <= list2.Val {
head = list1
head.Next = mergeTwoLists(list1.Next, list2)
} else {
head = list2
head.Next = mergeTwoLists(list1, list2.Next)
}
return head
}