Re: Linked Lists
Charlie Johnson wrote:
Hi all,
I am a novice programmer, and I have a question about the implementation of
linked lists. In every implementation of linked list I have seen, it's
always something like:
public class LinkedList
{
private int info; //for example
private LinkedList next; //here is the part I don't really get.
}
How can a class reference itself? It doesn't make sense to me. Could
someone please explain how this is possible?
The class doesn't reference itself. An object holds a reference to an object.
There is no reason an object can't hold a reference to itself; in fact, every
object does, known by the keyword 'this'.
Explicit references, like 'next' in your example, are almost always going to
point either to 'null', or to another instance of the class. That is another
separate instance of the same class.
So when you create a LinkedList *instance*, it holds a reference 'next' to
another LinkedList *instance*. Or to 'null'.
Let's flesh out the example.
<sscce name="LinkedNode.java" >
package testit;
public class LinkedNode <T>
{
private final T info;
private LinkedNode <T> next; // members start out null in Java
public LinkedNode( T value )
{
info = value;
}
public void setNext( LinkedNode <T> node )
{
this.next = node;
}
public LinkedNode <T> getNext()
{
return next;
}
public T getInfo()
{
return info;
}
public static void main( String [] args)
{
LinkedNode <Integer> head = new LinkedNode <Integer> ( 23 );
LinkedNode <Integer> another = new LinkedNode <Integer> ( 17 );
another.setNext( head );
head = another;
another = new LinkedNode <Integer>( 497 );
another.setNext( head );
head = another;
for( LinkedNode <Integer> walker = head;
walker != null;
walker = walker.getNext() )
{
System.out.print( " => " );
System.out.print( String.valueOf( walker.getInfo() ) );
}
System.out.println();
}
}
</sscce>
--
Lew