【发布时间】:2020-07-12 22:31:10
【问题描述】:
我遇到了一个非常奇怪的问题。我无法通过索引将节点插入自定义链表。所以这是我的方法:
public void Insert(int index, T item)
{
if(item == null)
throw new ArgumentNullException(nameof(item), "Item is equal null.");
if (index > Count || index < 0)
throw new ArgumentOutOfRangeException(nameof(index),"Index out of range.");
Item<T> newNode = new Item<T>(item);
Item<T> currentItem = Head;
if (index == 0)
{
newNode.Next = Head;
return;
}
var x = FindItemByData(this[index]);
while (currentItem.Next != null)
{
if (currentItem.Next == x)
{
currentItem.Next = newNode;
newNode.Next = FindItemByData(this[index]);
}
currentItem = currentItem.Next;
}
}
还有Item类:
public class Item<T>
{
public T Data { get; set; }
public Item<T> Next { get; set; }
public Item(T data)
{
Data = data;
Next = null;
}
}
我的链表的索引器从列表中的指定节点返回一个数据,所以我需要插入一个新节点来列出数据:item。例如:我有一个项目清单⛑ ???? ??? ????。我需要在索引 1 上插入 - 元素 ????,结果列表可能是 ⛑ ???? ??? ??? ????。
我试图证明这个问题并不简单,因为我找不到按索引插入的解决方案,总是只有'Insert before'。
我实现的方法不起作用。希望有人可以帮助我。
另外,还有这个方法的测试:
[TestCase(0)]
[TestCase(5)]
[TestCase(2)]
public void Insert_AtPositionValue_ReturnCount(int position)
{
//arrange
CustomList<int> list = new CustomList<int>(1, 2, 7, 8, 10);
//act
int elementToInsert = 100;
list.Insert(position, elementToInsert);
int count = list.Count;
int actualValue = list[position];
//arrange
Assert.Multiple(() =>
{
Assert.AreEqual(elementToInsert, actualValue, message: "Insert or Get Count work incorrectly ");
Assert.AreEqual(6, count, message: "Insert or Get Count work incorrectly ");
});
}
【问题讨论】:
标签: c# collections linked-list