【发布时间】:2017-09-21 00:24:52
【问题描述】:
我是 Scala 的新手,最近在 Leetcode 中提交我的 Scala 解决方案(143. Reorder List)时遇到了一个问题。
/**
* 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
而预期的输出是
[]
谁能教我如何得到这个正确的输出?
(“讨论”部分没有针对此问题的 Scala 解决方案)
这里是a link!
【问题讨论】:
-
[]在这种情况下是什么意思?什么是空的ListNode而不是null类型的ListNode变量? -
哦,原来是
ListNode,其中x是null? -
Int不能为空。 -
@Dima 当然。对不起,我的意思是一个空的单链表,它的头部是这个程序的输入参数。
-
我知道你的意思。我只是说,如果你的列表有一个头,它不能为空,因为它总是包含一些 int 值。