java - 一个Java链表类定义的解释

标签 java data-structures

我得到了以下 Java 类定义来实现一个单链表程序,但我无法理解完整的想法。我在代码中写了注释,提出了我对此的疑问。

// ******************************************************************
//                      Definition of class Node<T>.
// ******************************************************************
public final class Node<T>
{
    // This is a class with "generics" where T represents a type.
    // A final class cannot be extended.
    // A final variable behaves like a constant and can only be initialized at the time it is
    // declared or within a constructor.

    // I suppose this is the value of the node.
    public final T v; 

    // I do not understand this. How is "next" defined "recursively"?
    // Please help me visualize this situation.
    // Can this variable indicate the end of the list, maybe with a null value?
    public Node<T> next;

    // Constructor.
    public Node (T val, Node<T> link) {v = val; next = link}
}

最佳答案

// I suppose this is the value of the node.
public final T v; 

是的。 Nodeparameterized class它持有的实际数据类型称为 T .所以节点的值是一个具有这种类型的变量 T .我们可以有一个 Node<Integer>其中包含 Integer值也是一个Node<String>它将保存一个 String 值。 Node将以相同的方式运行。

// I do not understand this. How is "next" defined "recursively"?
// Please help me visualize this situation.
// Can this variable indicate the end of the list, maybe with a null value?
public Node<T> next;

在链表中,一个节点指向链表中的下一个节点。这就是它被称为“链接”列表的原因:有一串元素都链接在一起。我们可以说它是递归定义的,因为一个节点指向下一个节点,下一个节点又指向下一个下一个节点,等等。

当到达终点时,没有下一个节点所以它是null : 最后一个元素是 next = null .请注意,可能没有最后一个元素:一个节点可以指向第一个节点,它会创建一个循环列表。

例如,假设您要构建一个包含 2 个整数元素的链表。第一个元素将是 1,然后是 3。您可以编写以下内容:

Node<Integer> firstElement = new Node<>(1, new Node<>(3, null));
// here firstElement.v will be 1 and firstElement.next.v will be 3

关于java - 一个Java链表类定义的解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33708884/

相关文章:

Java 有界泛型 : Type inference bug?(方法调用,JLS 15.12.2.7)

java - JUnit 和测试文件

java - Spring 测试模块与 Mockito

c++ - XML 替换

c# - 何时在 C# 中使用 Stack<T> 集合?

algorithm - 在二叉树中找到最便宜的路径?

c++ - 输出二叉搜索树中叶节点的数量

optimization - 什么是写时复制?

java - 基于其他两个对象的子类创建一个对象

java - Spring Cloud Stream 与 RabbitMQ 的连接