Yes. The loop will exit when the first instance of the target is encountered.
Some applications might require only one copy of each value. But this program does not detect that.
Here is another node type:
public class StringNode { private String value; private StringNode next; public StringNode ( String word ) { value = word; // pointer to a String next = null; // pointer to a StringNode } public String getValue() { return value; } public StringNode getNext() { return next; } public void setValue( String val ) { value = val; } public void setNext( StringNode nxt ) { next = nxt; } public String toString() { return value ; } }
A StringNode
contains a reference to a String,
and a reference to the next node.
Here is how a StringNode
looks when it is part of a linked list.
There are two objects in the picture: the StringNode
and the String
it points to.
Here is a short program:
public class StringNodeTester { public static void main ( String[] args ) { StringNode node0 = new StringNode( "ant" ); System.out.println("Node 0: " + node0 ); } }
Here is what this short program creates:
The constructor for the Node
initializes the next
member to null
and copies a pointer to a String
into value
.
What does the program print?