We want to print on a PrintStream the elements of a list in the order in which they appear in the list (separating them by a ' ').
Example: For the list
A B C
We realize this operation through a static method that takes as parameters the reference to the first element of the list and a PrintStream.
public static void print(ListNode lis, PrintStream ps) { ListNode p = lis; while (p != null) { ps.print(p.info + " "); p = p.next; } ps.println(); }
Note that, in this case, we could have directly used lis to scan the list, since inside the method we do not need to access anymore the nodes we have already processed (i.e., printed out). We obtain the following implementation.
public static void print(ListNode lis, PrintStream ps) { while (lis != null) { ps.print(lis.info + " "); lis = lis.next; } ps.println(); }