What is the current element in a Scala DoubleLinkedList?

左心房为你撑大大i 提交于 2019-12-10 01:06:55

问题


I'm looking at using a DoubleLinkedList. It's remove() method says "Removes the current node from the double linked list." but there are no other references to current in the page.

What is the current node, how do I set it, and surely this can't be the only way of removing an item?


回答1:


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


来源:https://stackoverflow.com/questions/7764694/what-is-the-current-element-in-a-scala-doublelinkedlist

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