实体类:ListNode
public class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
链表实现:插入和打印 LinkedList
public class LinkedList {
ListNode head;
// 插入节点到链表尾部
public void insert(int val) {
ListNode newNode = new ListNode(val);
if (head == null) {
// 如果链表为空,新节点成为头节点
head = newNode;
} else {
// 否则,遍历到链表尾部并插入新节点
ListNode current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
}
// 打印链表
public void printList() {
ListNode current = head;
while (current != null) {
System.out.print(current.val + " -> ");
current = current.next;
}
System.out.println("null");
}
}
测试类:
public class LibraryTest extends TestCase {
@Test
public void testAddNode() {
LinkedList linkedList = new LinkedList();
linkedList.insert(2);
linkedList.insert(1);
linkedList.printList();
}
}
问题:
传入参数1时
此时的head结构是[2,null]


current.next=newNode更新后,为什么head也更新了?
从代码:ListNode current = head;
这代表着current和head指向同一对象,current发生改变,head也更新
4420

被折叠的 条评论
为什么被折叠?



