私は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);
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;
}
}
'* 'instancialized' *' – GurV
。 –