2

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

4

1 回答 1

3

我认为这是一个已知的错误

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).

于 2010-12-15T22:26:11.343 回答