scala刷LeetCode--21 合并两个有序链表

一、题目描述

将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 

二、示例

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

三、个人scala解题代码

 1 /**
 2  * Definition for singly-linked list.
 3  * class ListNode(var _x: Int = 0) {
 4  *   var next: ListNode = null
 5  *   var x: Int = _x
 6  * }
 7  */
 8 object Solution {
 9     def mergeTwoLists(l1: ListNode, l2: ListNode): ListNode = {
10         if (l1 == null) l2
11         else if (l2 == null) l1
12         else if (l1.x > l2.x) {
13             l2.next = mergeTwoLists(l1, l2.next)
14             return l2
15         } 
16         else {
17             l1.next = mergeTwoLists(l1.next, l2)
18             return l1
19         }
20     }
21 }

四、提交情况

执行用时 :524 ms, 在所有 Scala 提交中击败了100.00%的用户

内存消耗 :49.6 MB, 在所有 Scala 提交中击败了100.00%的用户

五、知识点

1. 尾递归

尾递归百度百科

 

 

黑白记忆▃

https://home.cnblogs.com/u/aCui/

posted on 2019-07-14 01:23  黑白记忆▃  阅读(274)  评论(0编辑  收藏  举报

导航