【发布时间】:2014-04-02 20:58:10
【问题描述】:
我正在学习链接数据结构,这个概念对我来说很有意义,但代码却没有。
我希望有人可以为我解释一下。
这是来自演讲幻灯片:
我这里有一个构造函数:
private static class Node<E> {
private E value;
private Node<E> next;
private Node( E value, Node<E> next ) {
this.value = value;
this.next = next;
}
}
Value- 存储实际信息。 Next- 存储对先前存储的对象的引用。说得通。
然后……
public void addFirst( E o ) {
Node<E> newNode = new Node<E>( o, null );
if ( head == null ) {
head = newNode;
} else {
newNode.next = head;
head = newNode;
}
}
上面的代码应该是添加元素。
但这是我的问题:newNode 已创建。 newNode.next 字段存储对对象头的引用。 (顺便说一句,我不知道在哪里声明了 head)然后:head=newNode.
所以 Head 现在有了 newNode 存储的值,而 head.next 现在正在引用自己?
这里的问题是head中的原始值丢失了,没有newNode的引用。
我错过了什么吗?
【问题讨论】:
-
您没有显示所有代码。显然
head必须在某处声明,可能在LinkedList类中? -
如果要添加到单链表的开头,新的头应该是新的节点。旧的头部应该在 head.next 中。该代码绝对可以简化。
-
"head.next = newNode" 对我来说更有意义。
-
head.next 对我来说更有意义。但上面的代码来自演讲幻灯片。所以应该没有什么问题。
-
很明显 head 是在类中的某处声明的,其中包含方法 addFirst
标签: java data-structures collections linked-list