链表指针作用域



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

例如:

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? 
}

在方法append中,行n = n.next不会影响作为参数传递的原始节点,在您的示例中为head为什么?因为Java是通过值传递的。这意味着,如果在方法内部修改head的引用(在方法内部被接收为n),它不会影响原始引用。因此,head将仍然引用内存中的相同位置(相同的对象)。

同样,你的方法test没有做任何事情,因为你正在创建一个局部变量:
Node next = ...;

,然后给它赋值n.next。但是这个变量只存在于那个方法内部,所以它不会影响它外部的任何东西。

next是一个属性,不是一个方法。您的test方法只是抓取对n.next的引用,它不是"移动头部"。

最新更新