简体   繁体   中英

Traversing a Doubly Linked Linked List in Java?

I am trying to traverse a doubly linked linked list but i seem to get an infinite loop. My goal is to find the first left most occurrence of an element in the list. I find the element but my program seems to keep looping. The only way to stop it from looping is breaking. There has to be another way. Thanks. {

    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");
    }

}

You need to advance in any case. Swap printing "no" and the next assignment:

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;
  }
}

Short variant if there are no loops and you want only one "YES" or "NO":

Node<E> temp;
temp = head;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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