LinkedList: Iterate and remove element

2019-08-11 08:13发布

问题:

In Scala, while iterating through the elements of a LinkedList, I would like to have some method remove() which removes the current element and (very important) makes the iterator point to the next element (or to the first if the current element is the last one; to null or something if there are no more elements).

回答1:

Not sure if this what you want but how about:

@annotation.tailrec
def round(xs: Set[(Int, Int)]) = {
    // here you might check if items are exhausted and possibly don't go through recursion deeper


    val suitable = xs.filter {
        case (x, i) => 
            println("Element "+x+" on position "+i)
            x != 0
    }

    // do something with suitable items

    round(xs.diff(suitable)) // next round with items that doesn't succeed in current round
}

val list = List(3,4,5)
round(list.zipWithIndex.toSet)