p != null
The condition of the while
tests if p
points to a Node
.
If so, the body of the loop uses that pointer.
p
is advanced through the list node by node.
Soon it reaches the last node, prints it out, and
p = p.getNext()
copies a null into p
.
This terminates the loop.
Here is the complete program. Compile and run it. Play with it. Make a longer linked list. (This program prints an extra comma at the end. You may wish to fix this.)
public class ChainMaker { public static void main ( String[] args ) { Node node0 = new Node( 223 ); Node node1 = new Node( 493 ); Node node2 = new Node( -47 ); Node node3 = new Node( 33 ); node0.setNext( node1 ); node1.setNext( node2 ); node2.setNext( node3 ); node3.setNext( null ); // not needed. Here as a reminder. // Traverse the Linked List in a loop Node p = node0; while ( p != null ) { System.out.print( p + ", " ); p = p.getNext(); } System.out.println( "\nEnd of List"); } }
Here is what the program prints:
C:\JavaSource> javac Node.java ChainMaker.java C:\JavaSource> java ChainMaker 223, 493, -47, 33, End of List C:\JavaSource>
Will the program work with a list of just one Node
?