当我创建一个链表节点,附加一些数据,然后在另一个方法中移动头部时,该头部在被调用方法中保持不变?链接列表指针范围
例如:
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?
}
你的'test'方法不会做**任何事情**。 –
头应该通过引用传递吧?在测试中,当我移动n = n.next时,该方法中的n.data = 4,但主要是,如何来 head.data = 5? – MiketheViking90
@ MiketheViking90“头部应该通过参考传递吗?”不,引用是按值传递的。 – Boann