我正在尝试重新排列单一链接列表。最初的清单是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;
}}
class LinkedLists {
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);
}}
head的值不会在行
处更改slowPointer = slowPointer.next;// why head value did not change
但是在行
slowPointer.next = null;// why did the head value change here
为什么会在这里改变。感谢。
答案 0 :(得分:0)
因为在第一种情况下,您要分配slowPointer旁边指向的对象。
但在第二种情况下,您正在修改引用slowPointer指向的对象的“next”值。因此头部对象被直接修改。