What is the current element in a Scala DoubleLinkedList?

独自空忆成欢 提交于 2019-12-04 23:53:12

A DoubleLinkedList is at the same time the list itself and a list node, similar to the :: for a regular List. You can navigate from one cell to the next or to the previous one with next and prev, respectively, and get the value of a cell with 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)

Be careful if you remove the first cell, as you’ll need to reassign your var holding the list to the next cell:

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!