p.getValue()%2 == 1
Recall that x%2 computes the remainder after the integer in x
is integer-divided by two.
Say that you want to search a linked list for a particular value. Here is a program that does that. The program looks at the nodes, one by one, in sequence. This is called linear search .
import java.util.* ;
public class LinearSearch
{
public static void main ( String[] args )
{
// Build a linked list
Node node0 = new Node( 2 );
Node node1 = new Node( 3 ); node0.setNext( node1 );
Node node2 = new Node( 5 ); node1.setNext( node2 );
Node node3 = new Node( 7 ); node2.setNext( node3 );
Node node4 = new Node( 11 ); node3.setNext( node4 );
Node node5 = new Node( 13 ); node4.setNext( node5 );
Node node6 = new Node( 17 ); node5.setNext( node6 );
Node node7 = new Node( 19 ); node6.setNext( node7 );
Node node8 = new Node( 23 ); node7.setNext( node8 );
Node node9 = new Node( 29 ); node8.setNext( node9 );
// Ask the user for a target
Scanner scan = new Scanner( System.in );
System.out.println("Number to search for: ");
int target = scan.nextInt();
// Traverse the Linked List in a loop.
// Stop when the target is found.
Node p = node0;
boolean found = false;
while ( p != null && !found )
{
if ( _______________ )
found = true;
else
p = p.getNext();
}
// Display the results
if ( found )
System.out.println( target + " is in the list." );
else
System.out.println( target + " is NOT in the list." );
}
}
Notice the somewhat tricky condition in the while:
while ( p != null && !found )
The loop ends when (1) the end
is reached, or
(2) the target is found.
The variable found helps with this.
When the loop exits, the pointer p is either null or points
to the node that holds the target.
What should fill the blank?
target == p.getNext() target = p.getValue() target == p.getValue()