用于计算链表中出现次数的算法

时间:2014-10-13 00:22:15

标签: algorithm list

对于无序链表,使用什么算法来计算特定数据的出现次数?

2 个答案:

答案 0 :(得分:0)

算法(伪代码):

node = list.head
count = 0
while node: # while we have a valid node
   if node.data == target_data:
      count++
   node = node.next  # assume this returns a "false" value if there is no next node

答案 1 :(得分:0)

我会使用从元素到计数的哈希映射映射来完成它。在伪代码中,它看起来像这样:

map = new HashMap()

for (item : list) {
  if map.has_key(item)
    ++map[item]
  else
    map[item] = 0
}

之后,对于每个项目,map [item]包含项目的出现次数。

如果你只想计算一个特定的项目,你也可以这样做

count = 0
for (item : list) {
  if (item == counted_item) {
    ++count
  }
}

然后count包含counts_item的出现次数。