我在scala中有2個鏈表,具有以下節點類定義:
class node(_x: Int = 0, nxt: node = null) {
var x = _x
var next = nxt
}
我想將兩個鏈接串列(將按升序排序)合并到第三個排序串列中。在 Scala 中執行此操作的最佳方法是什么。
我的解決方案:
object Solution {
def mergeTwoLists(list1: node, list2: node): node = {
(list1.x >= list2.x) match {
case true => ListNode(list2.x, mergeTwoLists(list1, list2.next))
case false => ListNode(list1.x, mergeTwoLists(list2, list1.next))
}
}
}
但是,當我運行它時,我得到以下 2 個串列 [1,2,4] [1,3,4] 的 nullPointerException
uj5u.com熱心網友回復:
如果您println((list1, list2))在函式的開頭放置 a ,您會發現在某些時候您正在Node(4,null)與null.
在修復它之前,您的代碼充滿了代碼異味和不遵循 Scala 最佳實踐的東西:
- 在 Scala 中,你不應該真的得到 NullPointerException,因為你永遠不應該故意使用
null. 這就是選項的用途。 - 定義類時使用大寫字母(即
Nodeovernode)。 - 您的類定義太過Java-y且過于復雜。它可以簡化為
case class Node(x: Int = 0, next: Node = null)(忽略不正確使用null)而沒有私有/公共變數的東西。 if您的函式中有一個不必要的模式匹配 - 它在技術上沒有任何問題,但是匹配真/假而不是使用陳述句有點奇怪(注意:主觀) 。
因此,要重新撰寫您的(仍然損壞的)函式,它看起來更像這樣:
case class Node(x: Int = 0, next: Node = null)
def mergeTwoLists(list1: Node, list2: Node): Node = {
if (list1.x >= list2.x) {
Node(list2.x, mergeTwoLists(list1, list2.next))
} else {
Node(list1.x, mergeTwoLists(list2, list1.next))
}
}
mergeTwoLists(Node(1, Node(2, Node(4))), Node(1, Node(3, Node(4))))
修復它:
- 更改類定義以使第二個引數可選(避免
null):
case class Node(x: Int = 0, next: Option[Node] = None)
- 更改您的函式以使第二個引數可選以解決此問題:
def mergeTwoLists(list1: Node, list2: Option[Node]): Node = {
???
}
- 您需要知道第二個串列是否存在。如果它是無,只回傳第一個串列。否則,繼續:
def mergeTwoLists(list1: Node, list2: Option[Node]): Node = {
list2 match {
case None => list1
case Some(list) => ???
}
}
- Finally, modify your original if/else to account for the new optional second parameter in the Node:
def mergeTwoLists(list1: Node, list2: Option[Node]): Node = {
list2 match {
case None => list1
case Some(list) =>
if (list1.x >= list.x) {
Node(list.x, Some(mergeTwoLists(list1, list.next)))
} else {
Node(list1.x, Some(mergeTwoLists(list, list1.next)))
}
}
}
Now, if you pass in your inputs you'll get a more sensible output:
mergeTwoLists(
Node(1, Some(Node(2, Some(Node(4))))),
Some(Node(1, Some(Node(3, Some(Node(4))))))
)
outputs
Node(1,Some(Node(1,Some(Node(2,Some(Node(3,Some(Node(4,Some(Node(4,None)))))))))))
Note: I don't know if this is the "best" way but it's how to solve your problem with the function you've given already. I'd also consider renaming the variables as list1, list2 and list are a bit confusing.
Scastie of it working: https://scastie.scala-lang.org/tUPoVzKpRRSJjZz62KsmhQ
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/440173.html
