// get the last value in the list // or return null public E getLast() { if ( isEmpty() ) return null; GenericNode<E> p = headPtr; while ( p.getNext() != null ) p = p.getNext(); return p.getValue(); }
Of course, the program should be tested:
public class GenericLinkedListTester { public static void main( String[] args ) { // create an empty generic linked list GenericLinkedList<Integer> list = new GenericLinkedList<>(); // insert some integers (autoboxed) list.insertFirst( 4 ); list.insertFirst( 3 ); list.insertFirst( 2 ); list.insertFirst( 1 ); list.traverse(); System.out.println("\n"); // test getFirst() System.out.println("First: " + list.getFirst() ); list.deleteFirst(); list.traverse(); System.out.println("\n"); System.out.println("New First: " + list.getFirst() ); // test getLast() System.out.println("Last : " + list.getLast() ); } }
PS C:\Code> javac GenericLinkedListTester.java PS C:\Code> java GenericLinkedListTester 1 2 3 4 First: 1 2 3 4 New First: 2 Last : 4 PS C:\CAI\java9Lessons\chap133\Private>
Seems to work. Industrial-grade testing would be much more thorough, though.
(Brain Teaser: ) Look at the first part of the code:
// create an empty generic linked list GenericLinkedList<Integer> list = new GenericLinkedList<>(); // insert some integers (autoboxed) list.insertFirst( 4 ); list.insertFirst( 3 ); list.insertFirst( 2 ); list.insertFirst( 1 );
How many objects are created?