Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the current element in a Scala DoubleLinkedList?

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?

like image 509
Duncan McGregor Avatar asked Oct 14 '11 07:10

Duncan McGregor


1 Answers

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
like image 178
Jean-Philippe Pellet Avatar answered Nov 15 '22 21:11

Jean-Philippe Pellet