0

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

}

3
  • put a break; in your if condition. If the value is found it won't come out of the loop and never reach that else statement. Commented Apr 9, 2016 at 22:48
  • @piyush121 i know of that solution but there must be another way. Commented Apr 9, 2016 at 22:53
  • @P.A. use a boolean variable, or return. Commented Apr 9, 2016 at 22:54

1 Answer 1

2

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");
Sign up to request clarification or add additional context in comments.

9 Comments

But your loop still keeps looping even if you have found the element. It fixes other bugs in the OP's code, but not that one.
it still seems to infinitely loop.
Well OP did not mention whether he needs all occurences or the first one.
Quote (emphasis mine): 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..
Could your list be a loop? I have added some more output for debugging and a simple loop check
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.