题目:将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
下面是做题详情
/**
* Definition for singly-linked list.
* class ListNode(_x: Int = 0, _next: ListNode = null) {
* var next: ListNode = _next
* var x: Int = _x
* }
*/
object Solution {
def mergeTwoLists(l1: ListNode, l2: ListNode): ListNode = {
if (l1 == null) {
return l2
} else if (l2 == null) {
return l1
}
if (l1.x < l2.x) {
ListNode(l1.x, mergeTwoLists(l1.next, l2))
} else {
ListNode(l2.x, mergeTwoLists(l1, l2.next))
}
}
}
在力扣上分析代码运行速度和内存,用的是递归解题的方法,执行速度一般,但是这个内存占用就很不够看了,不知道为什么内存消耗这么严重。有知道的小伙伴可以分享下~
力扣官网上其他人给出还有一种非递归的做法,可能看起来有些复杂,但是思路还是挺清楚的,大家可以看一下
/**
* Definition for singly-linked list.
* class ListNode(_x: Int = 0, _next: ListNode = null) {
* var next: ListNode = _next
* var x: Int = _x
* }
*/
object Solution {
def mergeTwoLists(l1: ListNode, l2: ListNode): ListNode = {
var head: ListNode = null
var node: ListNode = null
if(l1.x<=l2.x){
head = l1
}else{
head = l2
}
var n1 = l1
var n2 = l2
while(n1!=null&&n2!=null){
if(n1.x>n2.x){
while(n2!=null&&n1.x>n2.x){
node = n2
n2 = n2.next
}
node.next = n1
} else{
while(n1!=null&&n1.x<=n2.x){
node = n1
n1 = n1.next
}
node.next = n2
}
}
head
}
}
感谢作者codeplayer 给出的答案
链接:https://leetcode-cn.com/problems/merge-two-sorted-lists/solution/fei-di-gui-lian-biao-pin-jie-by-codeplayer/