Ever had those situations? Where all of a sudden something just works, but looking at the code you're certain that it shouldn't? For example, take this linked list method from Java:
public boolean insert(int n, E e) {
if(n < 0 || n > size) returnfalse;
Node<E> node = new Node();
node.data = e;
if(n == 0) {
node.next = head;
head = node;
size++;
returntrue;
} //THIS! Why did this work?? It looks like node.next will end up pointing at itself?
Node<E> current = head;
for(int i = 0; i < n - 1; i++) {
current = current.next;
}
node.next = current.next;
current.next = node;
size++;
returntrue;
}
Just some data. In this example, it's "Mopy" and points to node with data "Cottontail".
EDIT:
Cire, your explanation just made perfect sense. Not sure why I couldn't see that earlier.
EDIT2:
I actually think I keep getting confused on what head is. I keep thinking head is a node that has data, but then I think head is just a pointer to the first node that holds data?
One reason I dislike Java. I can't just look at the code and know if something is a pointer or not (or everything is, sometimes?). It bugs me. I'm about to write this all in C++ and add it to my data structs project on sourceforge.
That picture does help a lot, thanks. When I tried drawing this I kept screwing myself because I wasn't sure if head was a node or pointer to the first node.
In Java, you have nine primitive types. The 9th type is reference, which lets you reference null or some class type. References cannot reference primitive types, which is why references can't reference themselves (they are a primitive type) and like all primitive types they are passed by value.
Think of Java references as C++ pointers, except they always either point to valid data or null. I never think of an object as being the actual object, I always think of it being referenced.