Java 按值传递链表

Java 按值传递链表,java,linked-list,Java,Linked List,我正在尝试重新排列一个单链表。初始列表将为1,2,3,4,5 它们必须按1,5,2,4,3进行分类。我有代码,我正在努力理解它是如何工作的。基本上,我被java中传递值的概念所束缚 完整代码 public class Test { public static void main(String[] args) { LinkedLists linkedList = new LinkedLists(); linkedList.append(1); linkedList.app

我正在尝试重新排列一个单链表。初始列表将为1,2,3,4,5 它们必须按1,5,2,4,3进行分类。我有代码,我正在努力理解它是如何工作的。基本上,我被java中传递值的概念所束缚

完整代码

public class Test {
public static void main(String[] args) {

    LinkedLists linkedList = new LinkedLists();
    linkedList.append(1);
    linkedList.append(2);
    linkedList.append(3);
    linkedList.append(4);
    linkedList.append(5);
    linkedList.reorderList();

}}

class Node {
int data;
Node next;

public Node(int data) {
    this.data = data;
}}
类链接列表{

Node head;

public void reorderList() {
    if (head == null) {
        System.out.println(head);
        return;
    }
    Node slowPointer = head;
    Node fastPointer = head.next;
    System.out.println(slowPointer.hashCode());
    System.out.println(head.hashCode());
    while (fastPointer != null && fastPointer.next != null) {
        fastPointer = fastPointer.next.next;
        slowPointer = slowPointer.next;// why head value did not change
    }

    Node head2 = slowPointer.next;
    slowPointer.next = null;// why did the head value change here
    LinkedList<Node> queue = new LinkedList<Node>();
    while (head2 != null) {
        Node temp = head2;
        head2 = head2.next;
        temp.next = null;
        queue.push(temp);
    }
    while (!queue.isEmpty()) {
        Node temp = queue.pop();
        temp.next = head.next;
        head.next = temp;
        head = temp.next;
    }

}

public void append(int data) {
    if (head == null) {
        head = new Node(data);
        return;
    }
    Node current = head;
    while (current.next != null) {
        current = current.next;
    }
    current.next = new Node(data);
}}
但在第一线

slowPointer.next = null;// why did the head value change here

为什么会在这里更改。谢谢。

因为在第一种情况下,您将指定慢指针旁边的对象


但在第二种情况下,您修改的是参考慢指针指向的对象的“next”值。因此,直接修改head对象。

,因为在第一种情况下,您将指定慢指针指向的对象


但在第二种情况下,您正在修改引用slowPointer指向的对象的“next”值。因此直接修改head对象。

slowPointer=slowPointer.next;
正在为变量赋值。
slowPointer.next=null;
正在修改对象的状态。
slowPointer=slowPointer.next;
正在为一个变量赋值。
slowPointer.next=null;
正在修改一个对象的状态。请您再详细解释一下。我理解它仍然有点困难。slowPointer实际上是一个引用。它只指向一个节点对象。赋值完成后,=会发生变化它指向的对象。但是当使用“.”时,它会访问它当前指向的节点对象的属性,任何操作都会更改该对象中的实际蛋糕。请您详细解释一下。我仍然有点难以理解它。slowPointer实际上是一个引用。它只指向一个节点o对象。当赋值ie,=完成时,它会更改它指向的对象。但当使用“.”时,它会访问其当前指向的节点对象的属性,并且任何操作都会更改该对象中的实际蛋糕。
slowPointer.next = null;// why did the head value change here