这是来自 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 相同。