我正在尝试使用实现邻接列表
List<List<int>>
但每次我在某个索引中添加新元素时,整个内部列表都会计数跳跃例如:
List<List<int>> neighbours = new List<List<int>>();
List<int> emptyList= new List<int>();
for (int i = 0; i < 5; i++) {
neighbours.Add(emptyList);
neighbours[i].Add(0);
}
此时一切正常,list[anyIndex].count=1;
但是当我做的时候
neighbours[3].add(1);
所有list[anyIndex].count
跳到6知道发生了什么吗?
所有列表实际上都是一个相同的列表,因为添加了emptyList
。
相反,您需要创建new
:
neighbours.add(new List<int>());
如果你想使用像emptyList
这样可读的东西,你可以创建一个本地函数(C#7(:
List<int> emptyList() => new List<int>();
// ...
neighbours.Add(emptyList()); // creates always a new now
你可以试试这个:
List<List<int>> neighbours = new List<List<int>>();
for(int i=0 ; i < 5 ; i++){
neighbours.Add(new List<int>());
neighbours[i].Add(0);
}
for(int i=0 ; i < 5 ; i++){
Console.WriteLine(neighbours[i][0]);
}