gpt4 book ai didi

c# - 按索引向自定义链表添加节点,向右移动

转载 作者:行者123 更新时间:2023-12-04 04:02:29 25 4
gpt4 key购买 nike

我遇到了一个非常奇怪的问题。我无法按索引将节点插入到自定义链表中。所以这是我的方法:

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 - 元素🦋,结果列表可能是 ⛑ 🦋 🧶 🦚 🧥。
我试图表明这个问题并不简单,因为我找不到按索引插入的解决方案,总是只有“之前插入”。
我实现的方法不起作用。希望有人能帮我解决这个问题。
此外,还有对这种方法的测试:
        [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 ");
});
}

最佳答案

其实前一个作者很接近。但错误在于传递指向下一个元素的链接。

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;
Head = newNode;
Count++;
return;
}

for (int i = 0; i < index - 1; i++)
{
currentItem = currentItem.Next;
}

newNode.Next = currentItem;
currentItem.Next = newNode;
Count++;
}

关于c# - 按索引向自定义链表添加节点,向右移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62867086/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com