Java - 将一个节点添加到列表的末尾?

use*_*712 1 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

如何编写代码以在列表末尾添加节点?

所以,如果我有

head -> [1] -> [2] -> null
Run Code Online (Sandbox Code Playgroud)

我怎么去

head -> [1] -> [2] -> [3] -> null
Run Code Online (Sandbox Code Playgroud)

实际上......我甚至不确定我是否必须添加到最后.我认为添加然后排序是有效的吗?不确定.

谢谢!

Sea*_*oyd 5

public void addToEnd(Object data){
    Node temp = this;
    while(temp.next!=null)temp=temp.next;
    temp.next=new Node(data, null);
}
Run Code Online (Sandbox Code Playgroud)