- 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.
*/
typeListNodestruct {
Valint
Next*ListNode
}
funcmergeTwoLists1(l1*ListNode, l2*ListNode) *ListNode {
ifl1==nil {
returnl2
}
ifl2==nil {
returnl1
}
ret:=&ListNode{}
ifl1.Val<=l2.Val {
ret=l1
ret.Next=mergeTwoLists1(l1.Next, l2)
} else {
ret=l2
ret.Next=mergeTwoLists1(l1, l2.Next)
}
returnret
}
funcmergeTwoLists2(l1*ListNode, l2*ListNode) *ListNode {
head:=&ListNode{}
ret:=head
forl1!=nil&&l2!=nil {
ifl1.Val<l2.Val {
ret.Next=l1
l1=l1.Next
} else {
ret.Next=l2
l2=l2.Next
}
ret=ret.Next
}
ifl1!=nil {
ret.Next=l1
}
ifl2!=nil {
ret.Next=l2
}
returnhead.Next
}
// @lc code=end