链接列表指针范围

时间:2014-06-15 18:26:45

标签: java

为什么我创建一个链表节点,附加一些数据,然后用另一个方法移动头部,头部在callee方法中保持不变?

例如:

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 个答案:

答案 0 :(得分:1)

在方法append中,行n = n.next不会影响作为参数传递的原始节点,在您的情况head中。 为什么? Because Java is pass by value。这意味着如果在方法内部,您修改了head的引用(在方法中作为n接收),它将不会影响原始引用。因此,head仍将引用内存中的相同位置(同一对象)。

此外,您的方法test无法执行任何操作,因为您正在创建本地变量

Node next = ...;

然后为其分配n.next。但是这个变量只存在于该方法中,所以它不会影响它以外的任何东西。

答案 1 :(得分:0)

next是属性,而不是方法。您的test方法只是抓住对n.next的引用,而不是“移动头部。”

相关问题