# 算法：合并两个有序的链表

### 题目：合并两个有序链表

输入：1->2->4, 1->3->4



### 解答

1. 方法一：迭代
/**
* Example:
* var li = ListNode(5)
* var v = li.val
* class ListNode(var val: Int) {
*     var next: ListNode? = null
* }
*/
fun mergeTwoLists(l1: ListNode?, l2: ListNode?): ListNode? {
when{
l1==null&&l2==null -> return null
l1==null -> return l2
l2==null -> return l1
}
val listNode :ListNode? = ListNode(0)
var current = listNode
var point1 = l1
var point2 = l2
while (point1!=null&&point2!=null){
if (point1.val<point2.val){
current?.next = point1
point1 = point1.next
} else {
current?.next = point2
point2 = point2.next
}
current = current?.next
}
if (point1==null){
current?.next = point2
} else {
current?.next = point1
}
return listNode?.next
}

1. 方法二：递归
fun mergeTwoLists(l1: ListNode?, l2: ListNode?): ListNode?{
when{
l1==null&&l2==null -> return null
l1==null -> return l2
l2==null -> return l1
}
val list1 = l1
val list2 = l2
if (list1!!.val<list2!!.val){
list1.next = mergeTwoLists(list1.next,list2)
return list1
}else {
list2.next = mergeTwoLists(list2.next,list1)
return list2
}
}


05-30 537

04-30 4589

11-18 150

10-25 680

12-05 1万+

08-04 2万+

03-04 554

05-06 545

11-25 579

06-01 1万+

05-10 2611

05-30 400

05-19 911

10-21 354

04-18 1010

04-26 2709

10-21 333

03-20 1022

04-17 561

09-17 1252

04-14 60万+

03-13 15万+

02-19 18万+

03-01 14万+

03-04 14万+

03-06 4120

03-08 7万+

04-25 7万+

#### 总结了 150 余个神奇网站，你不来瞅瞅吗？

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客