在空的 LinkedList 中存储一个字符串值

发布于 2025-01-13 11:16:41 字数 574 浏览 3 评论 0原文

public class LinkedListExplained {


public Node head;
public Node tail;

public int size;

public LinkedListExplained() { // Constructor
    head = null;
    tail = null;
    size = 0;
}

public class Node{ // Inner Class
    String value;
    Node next;
}

public void add(String value){
    Node node = new Node();
    node.value = value;

    size++;
    if (head == null){
        head = node;
        tail = node;
        return;
    }
    tail.next = node;
    tail = node;

}

问题,当将单个 String 值存储到空 LinkedList 时,它是否会存储相同的值两次? 一次是头,一次是尾?

public class LinkedListExplained {


public Node head;
public Node tail;

public int size;

public LinkedListExplained() { // Constructor
    head = null;
    tail = null;
    size = 0;
}

public class Node{ // Inner Class
    String value;
    Node next;
}

public void add(String value){
    Node node = new Node();
    node.value = value;

    size++;
    if (head == null){
        head = node;
        tail = node;
        return;
    }
    tail.next = node;
    tail = node;

}

Question, when storing a single String value to an empty LinkedList, does it store the same value twice?
Once as head and once as tail?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

仅冇旳回忆 2025-01-20 11:16:41

不会。headtail 变量指向同一个 Node 对象。该对象包含一次String

No. The head and tail variables point to the same Node object. That object contains the String once.

岁月流歌 2025-01-20 11:16:41

如果你正在学习 Java,你首先需要了解的是,在 Java 中,所有看起来像对象的东西实际上都不是对象;相反,它是一个对象。它是一个指向对象的指针。当然,两个指针可能指向同一个对象。

因此,语句 public Node head; 并未声明 Node 的实例。它声明了一个指向 Node 实例的指针。这就是为什么你必须稍后使用 new Node(); 的原因。

因此,由于您将 headtail 指针都设置为指向 Node 的同一个实例,因此您可能有两个副本那个节点,但事实上你没有。您只有一个 Node 实例,并且有两个指向它的指针。

If you are learning Java, the first and foremost thing you need to understand is that in Java, everything that looks like an object is never actually an object; it is a pointer to an object. And of course two pointers may point to the same object.

So, the statement public Node head; does not declare an instance of Node. It declares a pointer to an instance of Node. That's why you have to use new Node(); later.

So, since you set both the head and the tail pointers to point to the same instance of Node, it might appear that you have two copies of that node, but in fact you do not. You only have one instance of Node, and you have two pointers pointing at it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文