【问题标题】:LinkedList: Iterate and remove elementLinkedList:迭代和删除元素
【发布时间】:2013-03-23 15:11:51
【问题描述】:

在 Scala 中,在遍历 LinkedList 的元素时,我希望有一些方法 remove() 删除当前元素并且(非常重要)使迭代器指向下一个元素(或者如果当前元素是最后一个;如果没有更多元素,则为 null 或其他内容)。

【问题讨论】:

  • 你为什么要这样做?或许你能解释一下这种需要的动机是什么?
  • 我需要依次遍历所有元素并选择一个最适合每一轮的元素。在某些时候,某些元素变得不活动,我想将它们从列表中删除。我想要恒定的移除时间(因此是链表),我还需要记住在最后一次迭代中选择的位置。您对数据结构有更好的建议吗?
  • 您是否有重复的项目或它们是独一无二的?

标签: scala iterator iteration


【解决方案1】:

不确定这是不是你想要的,但是怎么样:

@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)

【讨论】:

  • 但我们不会删除任何内容。这在性能上等同于遍历所有元素并检查每个属性是否仍然存在。我想在每一步都删除,因为列表可能很大,而且在每一步都有大量元素可能处于非活动状态。
  • @user1377000 你实际删除了:round(xs.diff(suitable)) 这里我只将那些不合适的值传递到下一轮。合适的将被垃圾收集。将xs.diff(suitable) 视为xs minus suitable
  • 的,没有看到差异。对此感到抱歉。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-18
  • 1970-01-01
相关资源
最近更新 更多