-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun.go
67 lines (61 loc) · 976 Bytes
/
run.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
62
63
64
65
66
67
package lists
import "fmt"
type ListNode struct {
Val int
Next *ListNode
}
func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
if l1 == nil {
return l2
}
if l2 == nil {
return l1
}
var head, node *ListNode
if l1.Val > l2.Val {
head, node = l2, l2
l2 = l2.Next
} else {
head, node = l1, l1
l1 = l1.Next
}
for l1 != nil && l2 != nil {
if l1.Val < l2.Val {
node.Next = l1
l1 = l1.Next
} else {
node.Next = l2
l2 = l2.Next
}
node = node.Next
}
if l1 != nil {
node.Next = l1
}
if l2 != nil {
node.Next = l2
}
return head
}
// PrintList print listnode
func printList(l *ListNode) {
for l != nil {
fmt.Println("Val:", l.Val)
l = l.Next
}
}
// 递归的方式
func mergeTwoLists2(l1 *ListNode, l2 *ListNode) *ListNode {
if l1 == nil {
return l2
}
if l2 == nil {
return l1
}
if l1.Val < l2.Val {
l1.Next = mergeTwoLists2(l1.Next, l2)
return l1
}
l2.Next = mergeTwoLists2(l1, l2.Next)
return l2
}