Java 在linkedlist中添加元素时发生了什么变化?
在LinkedList中,当访问下一个节点时,我的老师使用了以下方法:Java 在linkedlist中添加元素时发生了什么变化?,java,linked-list,Java,Linked List,在LinkedList中,当访问下一个节点时,我的老师使用了以下方法: public class LinkedList<T>{ private Node<T> header; private int size; public LinkedList(){ this.header=null; this.size=0; } public void add(T element){
public class LinkedList<T>{
private Node<T> header;
private int size;
public LinkedList(){
this.header=null;
this.size=0;
}
public void add(T element){
if(header==null){
header= new Node<T>(element);
}
else{
Node<T> current= header;
while(current.getNext()!=null){
current=current.getNext();
}
current.setNext(new Node<T>(element));
size++;
}
}
}
公共类链接列表{
专用节点报头;
私有整数大小;
公共链接列表(){
this.header=null;
这个。大小=0;
}
公共无效添加(T元素){
if(头==null){
header=新节点(元素);
}
否则{
节点当前=报头;
while(current.getNext()!=null){
current=current.getNext();
}
current.setNext(新节点(元素));
大小++;
}
}
}
有一段时间让我感到困惑的是,在代码片段中,我们似乎只在方法中创建的新
current
节点上操作,以遍历列表并添加元素。那么是什么使得实例变量this.header发生了变化?谢谢 在下面的代码段标题中,在添加第一个元素时设置变量
if(header==null){
header= new Node<T>(element);
}
if(头==null){
header=新节点(元素);
}
在对add
方法的后续调用中,首先将current
的值设置为header
(current
指向内存中header
也指向的相同位置)。当您使用current
变量在列表中遍历时,实际上是在遍历最初使用header存储的对象
到达最后一个节点时,此代码将添加新元素作为下一个节点。当前
变量的范围在else块中。但是,对于初学者来说,始终可以使用变量header
获取最新列表,当header
为null
时,它会更改为指向第一个元素。你看到了吗,是吗?那么是什么让实例变量变成了这个。headerchanged:没什么。向列表中添加新元素时,标题保持不变。新元素添加到列表的末尾,而不是开始。