我在 Java 的链表中工作,所以我试图掌握单个链表的概念。
head -> 12 -> 34 -> 56 -> null
head.next
将是 12(也与 node1 相同)。然而,什么是头呢?
更新: 引用和指针有什么区别?
Update2: So if head
is 12
and head.next
is 34
, then doesn’t mean this following function skips the first node to see如果它为空?
public void add(Object data, int index)
// post: inserts the specified element at the specified position in this list.
{
Node temp = new Node(data);
Node current = head;
// crawl to the requested index or the last element in the list,
// whichever comes first
for(int i = 1; i < index && current.getNext() != null; i++)
{
current = current.getNext();
}
// set the new node's next-node reference to this node's next-node reference
temp.setNext(current.getNext());
// now set this node's next-node reference to the new node
current.setNext(temp);
listCount++;// increment the number of elements variable
}
来源: http ://www.mycstutorials.com/articles/data_structures/linkedlists
原文由 Strawberry 发布,翻译遵循 CC BY-SA 4.0 许可协议
表头指的是表的第一个节点。它将为存储该节点引用的变量起一个好名字,如果列表为空,我希望它包含空引用
根据上下文,尾巴可以指代不同的事物。我惯用的术语是说尾部对应于
34 -> 56 -> null
在这个例子中,也就是头部后面的列表。在其他情况下,它可能是对最后一个节点的引用。在这样的解释中,尾部将指代您示例中的
56
节点。关于您的第一次编辑,这恰好是一个 _完全不同的问题_:
指针是对应于内存地址的值。引用是引用某个对象(或空值)的值。您不能对 Java 引用进行指针运算,但除此之外我会说它们非常相似。
可能会让您感到困惑的是,Java 中的变量 _永远不能包含对象_。对象总是存在于堆上,变量包含原始数据类型,或对堆上对象的引用。
关于您的第二次编辑:
在您提供的示例中,add 方法似乎跳过了第一个元素,从某种意义上说确实如此。这是因为实现有一个“虚拟”元素作为头部。查看构造函数中head-variable的初始化:
我不明白他们为什么决定这样做。对我来说,这看起来很愚蠢。