Java - 将一个节点添加到列表的末尾? [英] Java - add a node to the end of a list?
本文介绍了Java - 将一个节点添加到列表的末尾?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这就是我所拥有的:
public class Node{
Object data;
Node next;
Node(Object data, Node next){
this.data = data;
this.next = next;
}
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;
}
}
如何编写添加节点的代码列表的结尾?
How do I write the code to add a Node at the end of a list?
所以如果我有
head -> [1] -> [2] -> null
我如何到达
head -> [1] -> [2] -> [3] -> null
实际上......我甚至不确定是否必须添加到最后。我认为添加然后排序是有效的吗?不确定。
Actually...I'm not even sure if I have to add to the end. I think it's valid to add and then sort? Not sure.
谢谢!
推荐答案
public void addToEnd(Object data){
Node temp = this;
while(temp.next!=null)temp=temp.next;
temp.next=new Node(data, null);
}
这篇关于Java - 将一个节点添加到列表的末尾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文