21. 合并两个有序链表
作者:
邦_ | 来源:发表于
2022-07-07 09:43 被阅读0次
![](https://img.haomeiwen.com/i5047437/fc7749caa1b706f1.png)
截屏2022-07-08 09.42.34.png
func mergeTwoLists(_ list1: ListNode?, _ list2: ListNode?) -> ListNode? {
var temp1 = list1
var temp2 = list2
//添加虚拟头节点
var end :ListNode? = ListNode()
let ans = end
while temp1 != nil && temp2 != nil {
let n1 = temp1?.val ?? 0
let n2 = temp2?.val ?? 0
if n1 <= n2 {
end?.next = temp1
temp1 = temp1?.next
}else {
end?.next = temp2
temp2 = temp2?.next
}
end = end?.next ?? nil
}
//需要补个尾
end?.next = temp2 == nil ? temp1 : temp2
return ans?.next
}
本文标题:21. 合并两个有序链表
本文链接:https://www.haomeiwen.com/subject/yenmbrtx.html
网友评论