-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathsolution.go
59 lines (53 loc) · 931 Bytes
/
solution.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
package leetcode
/*
* @lc app=leetcode.cn id=21 lang=golang
*
* [21] 合并两个有序链表
*/
// @lc code=start
/**
* Definition for singly-linked list.
*/
type ListNode struct {
Val int
Next *ListNode
}
func mergeTwoLists1(l1 *ListNode, l2 *ListNode) *ListNode {
if l1 == nil {
return l2
}
if l2 == nil {
return l1
}
ret := &ListNode{}
if l1.Val <= l2.Val {
ret = l1
ret.Next = mergeTwoLists1(l1.Next, l2)
} else {
ret = l2
ret.Next = mergeTwoLists1(l1, l2.Next)
}
return ret
}
func mergeTwoLists2(l1 *ListNode, l2 *ListNode) *ListNode {
head := &ListNode{}
ret := head
for l1 != nil && l2 != nil {
if l1.Val < l2.Val {
ret.Next = l1
l1 = l1.Next
} else {
ret.Next = l2
l2 = l2.Next
}
ret = ret.Next
}
if l1 != nil {
ret.Next = l1
}
if l2 != nil {
ret.Next = l2
}
return head.Next
}
// @lc code=end