将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例
示例1 :
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
题解1:迭代
设置一个头节点,方便返回合并后的head
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
prehead := &ListNode{}
head := prehead
for l1 != nil && l2 != nil {
if l1.Val >= l2.Val {
head.Next = l2
l2 = l2.Next
}else{
head.Next = l1
l1 = l1.Next
}
head = head.Next
}
if l1 == nil {
head.Next = l2
}
if l2 == nil {
head.Next = l1
}
return prehead.Next
}
|
题解2:递归
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
if l1 == nil {
return l2
}
if l2 == nil {
return l1
}
var res *ListNode
if l1.Val <= l2.Val {
res = l1
res.Next = mergeTwoLists(l1.Next, l2)
}else{
res = l2
res.Next = mergeTwoLists(l1, l2.Next)
}
return res
}
|