[英]Explanation of a Java linked list class definition
我得到了以下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;
是。 Node
是一個參數化類 ,它所持有的實際數據類型稱為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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.