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

时间:2017-09-21 00:24:53

标签: scala singly-linked-list

我是Scala的新手,最近我在Leetcode中提交Scala解决方案(143。重新排序列表)时遇到了问题。

/**
 * 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

而预期的输出是

[]

任何人都可以教我如何获得正确的输出吗?

("讨论和#34;部分中没有Scala解决此问题的方法)

此处a link

1 个答案:

答案 0 :(得分:0)

<强>分辨

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

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

BTW,[]只是表达空值或非值的语言无关方式,因此,[]null之间没有区别。