This is a snippet from a linked list class from a textbook implementation:
public class ListItem
{
Object item;
ListItem next;
public ListItem(Object item)
{
this.item = item;
next = null;
}
}
It looks like recursion--class ListItem
has instance variable also named ListItem
. Is it proper to call this recursion?
Here's how I once defined a linked list in Pascal. I see a hint of what you might call recursion (pNodeType
, a.k.a. ^NodeType
), but it doesn't feel like what's above in the Java snippet :
type
**pNodeType** = ^NodeType ;
NodeType = record
name : string ;
next : **pNodeType** ; // conceptually, change the type to **^NodeType**
end ;
So I guess since Java lacks pointers and objects are references, I'm looking at the same thing after all. Right?
And so if I wanted a doubly-linked list (backward, too), I'd add an instance variable like so
ListItem prev;
and add a line of code to the constructor like so
prev = null;
and exercise the same amount of care that made the forward linkage work.
Right?
And finally if I wanted a generic linked list, I'd just change the snippet like so and change all occurrences of "Object" to "E" in the methods):
public class ListItem<E> {
E item;
ListItem next;
public ListItem(E item) {
this.item = item;
next = null;
}
}
Right?