【发布时间】:2017-03-02 23:17:40
【问题描述】:
无法理解链表。这是在java中。我正在写一些方法,添加,删除,查找。但是在这里想知道的是,被定义为类型 Node 的 Head 是实际的第一个 Node 吗?它是否包含数据和下一个节点引用?还是它以某种方式告诉第一个数据是什么?
谢谢
【问题讨论】:
标签: java linked-list
无法理解链表。这是在java中。我正在写一些方法,添加,删除,查找。但是在这里想知道的是,被定义为类型 Node 的 Head 是实际的第一个 Node 吗?它是否包含数据和下一个节点引用?还是它以某种方式告诉第一个数据是什么?
谢谢
【问题讨论】:
标签: java linked-list
head 节点是列表中的第一个节点。 tail 节点是列表中的最后一个节点。
两者都没有什么特别之处。
在您的LinkedList 类中,您可能引用了head 和tail,但节点本身只是节点。
【讨论】:
一般来说,不限于Java,所有列表节点都是一样的,“头”节点是列表中的第一个。这个“头”通常是一个变量,它是第一个列表节点的引用(或指针)。
一个简单的单链表节点可能看起来像
class ListNode
{
Object data; // The data added to the list
ListNode next; // Reference to the next item in the list
}
那么“头”就是
ListNode head;
也就是说,一个名为“head”的变量保存(引用)一个ListNode。
这个问题在 Java 中有些混乱,因为所有东西(除了像 int 这样的原语)都是 reference — 所以这看起来像 "head is a ListNode" 而实际上是 “head 是对列表节点的引用”.
从图形上看,如下所示,我将“数据”放在括号中并显示“下一个”指向某物。
head -> ListNode("foo")next -> ListNode("bar")next -> ListNode("baz")next -> null
当next 持有null 值时,会找到列表的末尾。您还必须有一个ListNode tail;,它将被更新为指向添加到列表中的最后一个东西。
这是一个非常简单(且未经测试)的概念示例。 Java 自己的java.util.LinkedList 要复杂得多,并且是用泛型参数化的。
class List
{
ListNode head = null;
ListNode tail = null;
public add(Object o)
{
ListNode node = new ListNode(o);
if (head == null) head = node; // if there's no head yet this is the head
if (tail != null) tail.next = node; // if there's a tail point tail at this new node
tail = node; // and this is the new tail
}
// need remove() etc other methods
}
【讨论】: