合并两个排序的链表
题目描述
输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
提示:
0 <= 链表长度 <= 1000
题目分析
两个链表都是有序的这就好办了,典型的归并排序,谁小谁先上的原则,没什么好说的,show the code:
fun mergeTwoLists(l1: ListNode?, l2: ListNode?): ListNode? {
val head = ListNode(0)
var now = head
var h1 = l1
var h2 = l2
while(h1 != null && h2 != null){
if(h1.`val` < h2.`val`){
now.next = h1
now = h1
h1 = h1.next
}else{
now.next = h2
now = h2
h2 = h2.next
}
}
if(h1 != null)
now.next = h1
if(h2 != null)
now.next = h2
return head.next
}
网友评论