简体   繁体   English

在链接列表中查找分钟

[英]Find min in Linked list

I'm trying to find the min in a linked list of Vertices. 我正在尝试在顶点的链接列表中查找分钟。 This is what I wrote, but it is faulty. 这是我写的,但这是错误的。 I don't get an error, but my program doesn't work and I think this is the source of the error. 我没有收到错误,但是我的程序无法运行,我认为这是错误的根源。 What am I doing wrong? 我究竟做错了什么?

      Iterator itr = vertices.iterator();
      Vertex smallest= getVertex(s);
      Vertex temp;
      while (itr.hasNext()){
          smallest=(Vertex)itr.next();
           if(itr.hasNext() && vertices.size()> 1 ){//there are at least 2 vertices left
                temp = (Vertex)itr.next();
                if (temp.distance< smallest.distance){
                    smallest = temp;
                }
          }
     }

The problem is that you are consuming two elements from the iterator on each iteration (via itr.next() ), so this means you are only comparing some elements: 问题在于,您每次迭代都要消耗迭代器中的两个元素(通过itr.next() ),因此这意味着您仅在比较一些元素:

1----2----3-----4-----5-----6
\----/    \-----/     \-----/

You compare 1 and 2; 您比较1和2; 3 and 4; 3和4; 5 and 6; 5和6; but not 2 and 3; 但不是2和3; 4 and 5. 4和5。

The easiest way to solve this is to keep the previous vertex: 解决此问题的最简单方法是保留先前的顶点:

Vertex prev = itr.next();
while (itr.hasNext()) {
  Vertex current = itr.next();

  // Compare prev and current

  prev = current;
}

Note also that you can avoid the casts (Vertex) if you declare the iterator with a type parameter: 还要注意,如果使用类型参数声明迭代器,则可以避免强制类型转换(Vertex)

Iterator<Vertex> itr = vertices.iterator();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM