Java 为什么这个链表插入代码有效,而另一个代码无效';T
我正在学习Java中的链表,我不明白这为什么不起作用:Java 为什么这个链表插入代码有效,而另一个代码无效';T,java,Java,我正在学习Java中的链表,我不明白这为什么不起作用: public static Node insert(Node head, int data) { if (head == null) return new Node(data); else { Node tail = head; while (tail != null) tail = tail.next; tail = new Node(data); retur
public static Node insert(Node head, int data) {
if (head == null) return new Node(data);
else {
Node tail = head;
while (tail != null) tail = tail.next;
tail = new Node(data);
return head;
}
}
虽然这很有效:
public static Node insert(Node head, int data) {
if (head == null) return new Node(data);
else {
Node tail = head;
while (tail.next != null) tail = tail.next;
tail.next = new Node(data);
return head;
}
}
在这两个代码中,都实例化了空端节点。为什么这不能产生相同的结果
节点类如下所示:
class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
将
节点
类更改为以下
class Node {
int data;
Node next;
Node(int d) {
this.data = d;
this.next = null;
}
}
在插入第一个节点时,将头部设置为新节点
public static Node insert(Node head, int data) {
if (head == null) {
head = new Node(data);
return head;
}
else {
Node tail = head;
while (tail.next != null) tail = tail.next;
tail.next = new Node(data);
return head;
}
}
第一个案例不起作用的原因是,下面将附加节点,而不是在它之后,而是您正在创建一个新节点,并将其分配给当前节点
while (tail != null) tail = tail.next;
tail = new Node(data);
在第一种情况下,您正在创建一个新的
节点
,但不在任何位置连接它,因此它将从列表中分离
在第二种情况下,您将创建一个新的节点
,并将其连接到实际的尾部节点
,因此它将附加到列表中
这里是一个图形表示:
当
tail.next
为空时,循环终止
然后你要这样做:
tail = new Node(data);
这会使最后一个非空尾部的next
指针保持为空
“实例化”
”在这两种情况下,对于head==null
情况,您忘记将head
设置到新节点。没有正确阅读问题。希望现在可以收回否决票。是的,但是在第一种情况下,如果(head==null)
,我将新节点分配给我的当前节点,head
,它就工作了。为什么?(反对票不是我的。)正确。当head为null时,表示列表为空或head指向null。因此,要插入第一个节点,您需要创建一个新节点并将其设置为head。循环在tail
为null时结束,而不是tail。next
。因此,末尾的nulltail
指针不应该为null。为什么tail
变为null?因为它被分配给最后一个非null的尾的下一个,它是null。为什么在第一种情况下尾
开始指向null,如果我设置尾=头
,是头
非null?@HugoB第一部分是在新节点(数据)
之前的情况,所以就在while
循环之后。在第一种情况下,在循环之后,tail
为null,因为这是while
循环的退出条件;换句话说,while(tail!=null)
意味着在循环之后tail
将是null
。但即使在第一种情况下tail
没有连接到任何东西,head
,它将被返回,它是否应该连接到tail
,并且有它的值?我的意思是,如果tail
假设tail.next
为空位置,则在通过新节点head
后,它是否应该到达上一个tail
指针,并通过它,tail.next
?当tail.next
为null
时,情况与o->o->null
不同,null
表示它没有指向任何东西,而不是指向null
的东西;情况与答案中的图像类似,因此o->o
。因此,当tail
假设“null
”时,它在内存中不是由tail指向的特殊位置。接下来,它只是意味着它什么都不是,与节点另一个节点=null
完全相同,因此tail=新节点(数据)
与另一个节点=新节点(数据)完全相同代码>,与列表没有关系<代码>尾部。下一个
仍然是null
,没有指向任何内容。
tail = new Node(data);
[head]---[1 (head.next)]---[2 (1.next)]---...---...---[last]---[nil (last.next)]