我正在尝试在 java
中实现一个 LinkedList
。目前,LinkedList
仅包含 2 个方法 insertAtFront
和 insertAtBack
,它们工作正常。但我想澄清一下我的概念,即当我们将新的 Node
分配给临时 head
时,它会在下一行更新原始 head
。
headTemp.reference = new Node(data);
这是怎么回事?因为默认情况下对象是引用类型。请用简单的英语解释这个概念。
节点类:
public class Node {
public int data;
public Node reference;
public Node(int data) {
// Calling the second constructor
this(data, null);
}
public Node(int data, Node reference) {
this.data = data;
this.reference = reference;
}
public int getData() {
return this.data;
}
public Node getNextNode() {
return this.reference;
}
}
链表类:
public class LinkedList {
// Head
protected Node head;
// Default head would be null
public LinkedList() {
this.head = null;
}
// insertAtFront first check if head is empty
public void insertAtFront(int data) {
if (isEmpty()) {
head = new Node(data);
} else {
head = new Node(data, head);
}
}
// insertAtBack
public void insertAtBack(int data) {
if (isEmpty()) {
head = new Node(data);
}
// If List has second node
else if (head.reference == null) {
head.reference = new Node(data);
} else {
Node headTemp = head;
while (headTemp.reference != null) {
headTemp = headTemp.reference;
}
headTemp.reference = new Node(data);
}
}
public boolean isEmpty() {
return this.head == null;
}
public void printList() {
System.out.printf("Linked list is : ");
Node headTemp = head;
while (headTemp != null) {
System.out.printf(" %s ", headTemp.data);
headTemp = headTemp.reference;
}
System.out.printf("\n");
}
}
主类:
public class Main {
public static void main(String[] args) {
LinkedList l = new LinkedList();
l.insertAtBack(23);
l.insertAtBack(24);
l.insertAtBack(25);
l.printList();
}
}
最佳答案
Java 变量作为对象(即 Node 实例)的值(引用)保存。 分配将共享对象。
因此,对对象的更改可以反射(reflect)在多个变量/字段中。
代码注释,插入非常好:
public void insertAtFront(int data) {
head = new Node(data, head);
}
//public LinkedList() {
// this.head = null;
//}
字段自动为 null、0、0.0、false。
类 Node 可能不需要公开。
关于java - LinkedList临时头更新原头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59835815/