题目:合并两个有序链表
将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-two-sorted-lists
分析
这道题目有两个做法,首先第一个是迭代这是做容易想到的。不断遍历,每次取出节点数字较小的拼接起来即可。
第二种方法是递归。每次分离出节点数字小的,然后把剩下继续递归,直到一方为空。
解答
- 方法一:迭代
/**
* Example:
* var li = ListNode(5)
* var v = li.`val`
* Definition for singly-linked list.
* 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
}
- 方法二:递归
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
}
}