Why does this work? :O

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public boolean insert(int n, E e) {
        if(n < 0 || n > size) return false;
        
        Node<E> node = new Node();
        node.data = e;
        if(n == 0) {
            node.next = head;
            head = node;
            size++;
            return true;
        } //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++;
        return true;
    }
What's in head initially?
Looks normal to me.

head points to the first node in the list (or null.)
make node.next point to the same node
make head point to node.

node is now the first node in the list.
Last edited on
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?
Last edited on
Yeah, I think it's your second edit that's causing it; thinking of head as a node, rather than a pointer.

It normally helps me a bit if I draw these things out.

http://s17.postimage.org/vq83tlsb3/image.png
Last edited on
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.
Last edited on
Topic archived. No new replies allowed.