如何在 Scala 中 return 一个空的单链表?

How to return an empty singly linked list in Scala?

我是Scala新手,最近在Leetcode提交问题(143.Reorder List)的Scala解决方案时遇到了问题

/**
 * Definition for singly-linked list.
 * class ListNode(var _x: Int = 0) {
 *   var next: ListNode = null
 *   var x: Int = _x
 * }
 */
object Solution {
    def reorderList(head: ListNode): ListNode = {
        val hd: ListNode = head
        if (head == null || head.next == null || head.next.next == null) head
        // find middle in [1,2,3,4,5]
        else {
            var runner: ListNode = head
            var walker: ListNode = head
            while (runner.next != null && runner.next.next != null) {
                runner = runner.next.next
                walker = walker.next
            }
            val mid: ListNode = walker // 3
            var secondHead: ListNode = mid.next // 4
            mid.next = null // now we have [1,2,3,null]
              // Reverse second part 
            secondHead = reverse(secondHead) // [5,4,null]
              // dummy node link to head
            val dummy: ListNode = new ListNode(0)
            dummy.next = head
              // Connect 
            var firstHead: ListNode = head
            while (secondHead != null) {
                val tmp: ListNode = secondHead.next
                secondHead.next = firstHead.next
                firstHead.next = secondHead
                firstHead = firstHead.next.next
                secondHead = tmp
            }
            dummy.next
        }
    }

    def reverse(head: ListNode): ListNode = {
        if (head == null || head.next == null) head
        else {
            var newHead: ListNode = null
            var curHead: ListNode = head
            while (curHead != null) {
                val tmp: ListNode = curHead.next
                curHead.next = newHead
                newHead = curHead
                curHead = tmp
            }
            newHead
        }    
    }
}

但是说到输入的测试用例

[]

这是一个空的ListNode,那么我的Scala代码的输出是,

null

而预期输出是

[]

谁能教我如何获得正确的输出?

("Discussion"部分没有Scala解决这个问题)

这里是a link

已解决

LeetCode 最近才开始支持 Scala 解决方案,并且有一些小问题需要解决。这就是其中之一。

他们现在已经解决了这个问题,我已经确认它可以解决(~20 行 Scala 代码)。

顺便说一句,[] 只是一种与语言无关的表达空值或非值的方式,因此,从本质上讲,[]null 之间没有区别。