Scala DoubleLinkedList中的当前元素是什么?

Dun*_*gor 13 scala scala-collections

我期待在使用一个DoubleLinkedList.它的remove()方法说"从双链表中删除当前节点".但页面中没有其他对当前的引用.

什么是当前节点,如何设置它,当然这不是删除项目的唯一方法?

Jea*_*let 16

A DoubleLinkedList同时是列表本身列表节点,类似于::常规列表节点List.您可以分别使用next和从一个单元格导航到下一个单元格或前一个prev单元格,并获取单元格的值elem.

scala> val list = collection.mutable.DoubleLinkedList(1,2,3,4,5)
list: scala.collection.mutable.DoubleLinkedList[Int] = DoubleLinkedList(1, 2, 3, 4, 5)

scala> list.next.next.remove() // list.next.next points on 3rd cell

scala> list
res0: scala.collection.mutable.DoubleLinkedList[Int] = DoubleLinkedList(1, 2, 4, 5)
Run Code Online (Sandbox Code Playgroud)

如果删除第一个单元格,请小心,因为您需要将保存列表的var重新分配给下一个单元格:

scala> val list = collection.mutable.DoubleLinkedList(1,2,3,4,5)
list: scala.collection.mutable.DoubleLinkedList[Int] = DoubleLinkedList(1, 2, 3, 4, 5)

scala> list.remove() // remove first item

scala> list // this is now a 'dangling' cell, although it still points to the rest of the list
res6: scala.collection.mutable.DoubleLinkedList[Int] = DoubleLinkedList(1, 2, 3, 4, 5) // uh? didn't I remove the first cell?

scala> list.next.prev // we can check that it is not pointed back to by its next cell
res7: scala.collection.mutable.DoubleLinkedList[Int] = null
Run Code Online (Sandbox Code Playgroud)

  • 很好的答案 - 有点遗憾,文档不如StackOverflow好! (5认同)