遍历Java中的双链接链表



我试图遍历一个双链接列表,但似乎得到了一个无限循环。我的目标是找到列表中元素最左边的第一个位置。我找到了元素,但我的程序似乎一直在循环。阻止它循环的唯一方法是中断。必须有另一种方法。谢谢{

    Node<E> temp;
    temp = head;
    while(temp.next != null){
        if(temp.value==obj){
            System.out.println("YES");
        }
        else{
            temp = temp.next;
        }
        System.out.println("nNO");
    }

}

在任何情况下都需要进步。交换打印"否"和下一个任务:

Node<E> temp = head;
while(temp != null) {   // Don't check for next here or miss the last element
  if (temp.value == obj) {
    System.out.println("YES: " + value);
    break;
  } 
  System.out.println("NO: " + value);
  temp = temp.next;
  // Loop check (if needed)
  if (temp == head) {
    break;
  }
}

如果没有循环并且您只想要一个"是"或"否",则为短变体:

Node<E> temp;
temp = head;
while (temp != null && temp.value != obj) {
  temp = temp.next;
}
System.out.println(temp == null ? "NO" : "YES");

最新更新