Java 实现单链表时出现莫名其妙的赋值
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 也有值了

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 也有值了
...全文
相关推荐
Java单链表增删改查的实现
Java实现单链表的增删改查以及选择、冒泡、反转排序等功能的实现!
基于JAVA的单链表简单实现
基于JAVA创建单链表,并实现了在队列末尾增加、删除元素,在队列中插入、删除元素,打印链表。
java实现数据结构单链表示例(java单链表)
主要介绍了java数据结构实现单链表示例,需要的朋友可以参考下
Java实现单链表的基本操作
Java实现单链表的基本操作
Java实现单链表以及单链表的操作.zip
通过Java实现单链表的操作,包括单链表定义、遍历、置空、判空、插入、删除、反转、中间结点、指定顺序排序、前插、后插、判断单链表是否存在环、环的长度、环的起始结点


