Search code examples
javalinked-listconditional-operator

The ternary operator in Java Linked list Search method


i got a Syntax error on token "=", != expected in temp = temp.next

Here's the rest of the code

static boolean search(int xData) {

    Node temp = head; 

    while (temp != null) {
        return (temp.data == xData ) ? true : temp = temp.next;
    }

    return false;
}

Solution

  • You are trying to write something that can't be done with the conditional operator.

    Instead:

    if (temp.data == xData) return true;
    temp = temp.next;
    

    return (temp.data == xData )? true : temp = temp.next ;
    

    Will always return. It is a return statement, after all. So, your loop would only ever iterate once.

    You could have parenthesized the assignment:

    return (temp.data == xData )? true : (temp = temp.next);
    

    However:

    • You're reassigning a local variable immediately before returning - what's the point?
    • The type of the expression isn't Boolean, so it's not compatible with the return type of the method.

    A nicer way to write this would be using a for loop:

    for (Node temp = head; temp != null; temp = temp.next) {
      if (temp.data == xData) return true;
    }
    return false;