ListGenerator接受int类型的数组,并将其转换为递归对象。
public class ListNode
{
public int val;
public ListNode next;
public ListNode(int x) { val = x; }
public ListNode(int val = 0, ListNode next = null)
{
this.val = val;
this.next = next;
}
}
public static ListNode GenerateList(int[] nums)
{
if (nums == null || nums.Length == 0) { return null; }
var i = 0;
var first = new ListNode(nums[i]);
var current = first;
while (++i < nums.Length)
{
current.next = new ListNode(nums[i]);
current = current.next;
}
return first;
}
我知道c#中的类是引用类型,所以在执行这行代码current.next = new ListNode(nums[i]);
之后,first
变量的值将与current
相同,一切都很好。
但current = current.next;
之后first
和current
的值不相同。实际上,next
属性在first
中有一个值,但在current
中为空。我不明白为什么会这样。在我看来,first
必须与current
相同,但它不是。
对于var current = first;
,您将first
中的引用复制到current
。在这一点上,它们指的是同一个对象。current.next
中的任何变化都可以在first.next
中看到。
之后你重新赋值current
,所以现在它指向first
以外的东西。first
中的引用不受影响。