Of course.
Here is a generic linked list.
The logic of the list is the same as in a linked list of int
,
but now the particular type is given as a type variable E
.
public class GenericLinkedList<E> { private GenericNode<E> headPtr = null; // The constructor creates an empty list public GenericLinkedList() { headPtr = null; } // Determine if the List is empty public boolean isEmpty() { return headPtr == null; } // Delete the entire list // public void deleteList() { if ( headPtr != null ) { headPtr =null; } } // Insert one GenericNode containing data at the head // of the list. public void insertFirst( E data ) { GenericNode<E> newFirst = new GenericNode<E>( data ); newFirst.setNext( headPtr ); headPtr = newFirst; } // Delete the first node of the list // public void deleteFirst() { if ( headPtr != null ) { headPtr = headPtr.getNext(); // headPtr now points at second node, or // is null if there was no second node. } } // Traverse the list, printing each node public void traverse() { GenericNode<E> p = headPtr; while ( p != null ) { System.out.print( p + " "); p = p.getNext(); } } // get the first value in the list // or return null public E getFirst() { if ( isEmpty() ) return null; return headPtr.getValue(); } }
The type variable E
is given in the declaration of the class:
public class GenericLinkedList<E>
The same variable declares the type of node that the list is made of:
private GenericNode<E> headPtr = null;
and is used to specify the type of parameters for functions:
public void insertFirst( E data )
When a list is constructed,
a class name is given for the type variable E
,
and that class name is used wherever E
appears,
including the type of GenericNode
.
So declaring
GenericLinkedList gList<Integer> = new GenericLinkedList<>() ;
creates a a list of GenericNode
s of Integer
s.
Declaring
GenericLinkedList gList<Bird> = new GenericLinkedList<>() ;
creates a list of GenericNode
s of Bird
s.
A getLast()
method might be useful. Luckily, you can write it:
// get the last value in the list // or return null public getLast() { if ( isEmpty() ) return null; GenericNode p = headPtr; while ( p. != null ) p = p.getNext(); return p.getValue(); }