2014-06-15 191 views
-2

当我创建一个链表节点,附加一些数据,然后在另一个方法中移动头部时,该头部在被调用方法中保持不变?链接列表指针范围

例如:

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

你的'test'方法不会做**任何事情**。 –

+0

头应该通过引用传递吧?在测试中,当我移动n = n.next时,该方法中的n.data = 4,但主要是,如何来 head.data = 5? – MiketheViking90

+0

@ MiketheViking90“头部应该通过参考传递吗?”不,引用是按值传递的。 – Boann

回答

0

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

1

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

另外,你的方法,因为你正在创建一个局部变量test没有做任何事情:

Node next = ...; 

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

+0

“行n = n.next不会影响原始节点n ... n仍然会引用内存中的相同位置”。这是极具误导性的。该代码在该方法中完美地工作。 – Boann

+0

@Boann编辑澄清。现在呢? – Christian