Java 实现单链表时出现莫名其妙的赋值

野路子程序员 野路子程序员 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
Java 实现单链表,OK倒是OK了,但是就是不知道这个 head 是什么时候被赋值的?我根本就没有给 head 这个玩意赋值啊,用 deBug观察,发现每次添加完了,head 就不是 null 了,求各路大神指点

public class Node {
private Object data;//数据域
private Node next;//链域

public Node(Object data) {
this.data = data;
this.next = null;
}

public Object getData() {
return data;
}

public void setData(Object data) {
this.data = data;
}

public Node getNext() {
return next;
}

public void setNext(Node next) {
this.next = next;
}

}


public class List {
private Node head;//链表的头节点

public List() {
head = new Node(null);
}

//添加节点
public void add(Node n){
Node p = head;
while(p.getNext() != null){
p = p.getNext();
}
p.setNext(n);
}

//遍历链表
public void display(){
Node p = head.getNext();
while(p != null){
System.out.println(" Data : " + p.getData());
p = p.getNext();
}
}
}

//测试方法
public class Test {
public static void main(String[] args) {

Node head = new Node(null);

Node p = head;

p.setNext(new Node(1));

System.out.println(head.getNext().getData());

}
}

控制台打印 1 ,但是我是给 p 的 next 赋值的啊,跟 head 没关系啊,为什么 head 也有值了
...全文
评论 5
收藏 已收藏
分享
返回顶部
野路子程序员
Java 51,407 成员 86,128 内容