这是来自2.8.1
的Scala标准库的来源 /** Append linked list `that` at current position of this linked list
* @return the list after append (this is the list itself if nonempty,
* or list `that` if list this is empty. )
*/
def append(that: This): This = {
@tailrec
def loop(x: This) {
if (x.next.isEmpty) x.next = that
else loop(x.next)
}
if (isEmpty) that
else { loop(repr); repr }
}
/** Insert linked list `that` at current position of this linked list
* @note this linked list must not be empty
*/
def insert(that: This): Unit = {
require(nonEmpty, "insert into empty list")
if (that.nonEmpty) {
next = next.append(that)
}
}
这最后一行不应该是next = that.append(next)
吗? (即将此链表的其余部分放在我们插入的列表的末尾?
如果没有,为什么不呢?代码当前将我们插入的列表附加到当前列表的末尾 - 即与apppend相同。
答案 0 :(得分:3)
我认为这是known bug。
scala> import scala.collection.mutable._
import scala.collection.mutable._
scala> val foo = LinkedList(1, 2, 3, 4)
foo: scala.collection.mutable.LinkedList[Int] = LinkedList(1, 2, 3, 4)
scala> foo.next insert LinkedList(5, 6, 7, 8)
scala> foo
res2: scala.collection.mutable.LinkedList[Int] = LinkedList(1, 2, 3, 4, 5, 6, 7, 8)
如果假设在“当前位置”插入LinkedList(5, 6, 7, 8)
,则最终结果应为LinkedList(1, 5, 6, 7, 8, 2, 3, 4)
。