【发布时间】:2018-10-06 02:41:34
【问题描述】:
我有这个用于单链表的代码,它可以工作。我从理论上理解单链表的原理,但是当涉及到代码时,我不明白指针是如何工作的。我的问题在于这两行代码,这是最后提到的代码的一部分
p.next = new Node<>(a[i], null);
p = p.next;
为什么我们通过p调用next并创建新节点然后通过参数同时将null分配给next。?然后给出 p.next 的 p 值,它应该为空?我试图打印出 p.next 和 next 以查看它们是否相同或存在差异,并且我在控制台中获得了 p.next 的地址和 next 的地址。它们有何不同?我需要在这部分代码中解释一下节点和指针是如何创建的。
public class EnkeltLenketListe<T> implements Liste<T> {
private static final class Node<T>
{
private T value;
private Node<T> next;
private Node(T value, Node<T> next)
{
this.next = next;
this.value = value;
}
}
private Node<T> head, tail;
private int counter;
public EnkeltLenketListe(T[] a)
{
this();
int i = 0; for (; i < a.length && a[i] == null; i++);
if (i < a.length)
{
head = new Node<>(a[i], null);
Node<T> p = head;
counter = 1;
for (i++; i < a.length; i++)
{
if (a[i] != null)
{
p.next = new Node<>(a[i], null);
p = p.next;
counter++;
}
}
tail = p;
}
}
【问题讨论】:
-
您将一个新节点分配给
p.next,然后将p设置为这个新节点。 -
但在我将 p 设置为新节点之前,我将参数中的 null 发送到构造函数,然后更改为 null 所以不应该 p = p.next = null;还有吗?
-
p不是您的新对象。请了解 OOP 的基础知识。 -
那么 p.next 是什么?
-
你的新
Node。
标签: java algorithm pointers nodes