將兩個有序鏈表合併爲一個新的有序鏈表並返回。新鏈表是經過拼接給定的兩個鏈表的全部節點組成的。 ui
輸入:1->2->4, 1->3->4
輸出:1->1->2->3->4->4spa
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%的用戶scala
內存消耗 :49.6 MB, 在全部 Scala 提交中擊敗了100.00%的用戶code
尾遞歸百度百科blog