-2

How come when I create a linked list node, append some data, then move the head in another method, the head stays the same in the callee method?

For example:

public static void append(Node n, int d) {
    while (n.next != null) {
        n = n.next;
    }

    n.next = new Node(d);
}

public static void test(Node n) {
    n = n.next;
}

public static void main(String[] args) {
    Node head = new Node(5);
    append(head, 4);
    append(head, 3);

    test(head); //this moves the head to head.next
    //why is head still = 5 after we get here? 
}

2 Answers2

1

In the method append, the line n = n.next won't affect the original node passed as argument, in your case head. Why? Because Java is pass by value. This means that if inside the method, you modify the reference of head (which is received as n inside the method), it won't affect the original reference. Therefore, head will still refering to the same location in memory (the same object).

Also, your method test doesn't do anything because you are creating a local variable:

Node next = ...;

and then assigning n.next to it. But this variable only exists inside that method, so it won't affect anything outside it.

Community
  • 1
  • 1
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
  • "the line n = n.next won't affect the original node n ... n will still refer to the same location in memory". This is highly misleading. That code works perfectly well within the method. – Boann Jun 15 '14 at 18:35
0

next is a property, not a method. Your test method is just grabbing the reference to n.next, it is not "moving the head."

Igor
  • 33,276
  • 14
  • 79
  • 112