-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathmerge_two_lists.go
61 lines (52 loc) · 889 Bytes
/
merge_two_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
58
59
60
61
package linkedlist
func MergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode {
if list1 == nil {
return list2
}
if list2 == nil {
return list1
}
var p1 = list1
var p2 = list2
var dummy = &ListNode{}
var p = dummy
for {
if p1.Val <= p2.Val {
p.Next = p1
p1 = p1.Next
} else {
p.Next = p2
p2 = p2.Next
}
p = p.Next
if p1 == nil || p2 == nil {
break
}
}
if p1 != nil {
p.Next = p1
}
if p2 != nil {
p.Next = p2
}
return dummy.Next
}
func MergeTwoListsWithRecursion(list1 *ListNode, list2 *ListNode) *ListNode {
if list1 == nil {
return list2
}
if list2 == nil {
return list1
}
if list1.Val <= list2.Val {
return &ListNode{
Val: list1.Val,
Next: MergeTwoListsWithRecursion(list1.Next, list2),
}
} else {
return &ListNode{
Val: list2.Val,
Next: MergeTwoListsWithRecursion(list1, list2.Next),
}
}
}