java - 在Java中构建链表

标签 java list linked-list

这是我书中的一个例子。正如我所见,当您使用此类创建列表时,您创建了两个对象(firstlast,均为 null)。当您将第一个和最后一个“Node”对象放入 add 方法中时,我不明白为什么。当您同时设置 first = nlast = n 时,它不应该创建两个元素吗?例如,如果我调用 list.add(2),那么 firstlast 现在不应该都是 2 吗?

public class List {

    private Node   first = null;
    private Node   last = null;

    public List(){
        first = null;
        last = null;

    }   

    private static class Node{

        public int   value;
        public Node   next;

        public Node ( int value, Node next){
            this.value = value;
            this.next = next;       
        }
    }   

    public void add (int value){
        Node   n = new Node (value,null);

        if(first==null){
            first = n;
            last = n;

        }else{
            last.next = n;
            last = n;
        }
    }

    public int size(){
        int   number = 0;
        Node   n = first;
        while(n != null){
            number++;
            n = n.next;
        }
        return number;
    }
}

最佳答案

As i see it, when u create a list with this class, you create two objects (first and last, which are null).

这不是真的。 firstlast 不是对象,而是对对象的引用。在本例中,它们以 null 引用开始,这意味着它们根本不引用任何对象。

当你写 first = n; 时last = n;,您将 firstlast 设置为都引用同一个对象 - 无论 n 引用什么对象。

For example, if list.add(2), shouldn't now both first and last be 2?

是的,它们都引用同一个 Node 实例,其 value 为 2。

关于java - 在Java中构建链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8931461/

相关文章:

python - 多维数组与 python 中的嵌套列表

Python-如何根据列表中是否出现返回索引

python - 为什么我得到 None 值,并且为什么该数字仍在 Python 中打印?

c - 使用已排序的链表进行顺序搜索

c - 如何打印链表中除最后一个元素之外的每个元素

c - 为什么在创建链接列表节点的函数中传递结构指针参数不起作用?

java - 在 Java 中导入自定义类,使用命令行

java - EJB 注入(inject)不起作用

java - 如何从 java spring-boot 应用程序调用 GraphQL api?是否有支持 graphQL 查询形成的注释?

java - 如何获得循环内每个商品的总销售成本?