-
Notifications
You must be signed in to change notification settings - Fork 1
/
merge-two-sorted-lists.go
57 lines (47 loc) · 1.03 KB
/
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
47
48
49
50
51
52
53
54
55
56
57
package algorithms
import (
"github.com/goldennovember/leetcode-go/gods"
)
type LinkedList = gods.LinkedList
type ListNode = gods.ListNode
func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode {
// If one of the list is empty, return the other list
if list1 == nil {
return list2
}
if list2 == nil {
return list1
}
ans := LinkedList{}
var node *ListNode
// Compare the first node of each list
// Take the smaller one as the head of the answer list
if list1.Val > list2.Val {
ans.Head = list2
node = list2
list2 = list2.Next
} else {
ans.Head = list1
node = list1
list1 = list1.Next
}
// Compare the elements of the two lists until one of them is empty
for list1 != nil && list2 != nil {
if list1.Val > list2.Val {
node.Next = list2
list2 = list2.Next
} else {
node.Next = list1
list1 = list1.Next
}
node = node.Next
}
// If one of the list is not empty, append it to the answer list
if list1 != nil {
node.Next = list1
}
if list2 != nil {
node.Next = list2
}
return ans.Head
}