C# 如何在C中的单链表中的索引处添加元素#
我正在用C#实现链表数据结构。我面临以下问题 当我试图在单链表的索引中添加元素时,它就不起作用了 下面是我的代码。问题在函数AddToIndex中。它不能正常工作 节点 链接列表C# 如何在C中的单链表中的索引处添加元素#,c#,data-structures,linked-list,singly-linked-list,C#,Data Structures,Linked List,Singly Linked List,我正在用C#实现链表数据结构。我面临以下问题 当我试图在单链表的索引中添加元素时,它就不起作用了 下面是我的代码。问题在函数AddToIndex中。它不能正常工作 节点 链接列表 public class DLinkedList { public int data; public DNode Next { get; set; } public DNode Head { get; private set; } public DNode Tail { get; pri
public class DLinkedList
{
public int data;
public DNode Next { get; set; }
public DNode Head { get; private set; }
public DNode Tail { get; private set; }
public int Count { get; set; }
public void AddToHead(int element)
{
DNode temp = new DNode(element);
temp.next = Head;
Head = temp;
Count++;
if (Count == 1)
{
Tail = Head;
}
}
public void AddToIndex(int element, int index)
{
DNode temp = new DNode(element);
for (int i = 1; i < index - 1; i++)
{
Head = Head.next;
}
temp.next = Head;//in this case infinite link list
//temp.next = Head.next; in this case one element is removed.
Head.next = temp; // whole link list is not created, partial linked list created
}
public void Display()
{
DNode temp = Head;
while (temp != null)
{
System.Console.WriteLine(temp.data);
temp = temp.next;
}
}
}
控制台上的结果:
---加头---
11
10
7.
5.
---调用AddToIndex函数后--
7.
12
五,
注意:我只是在构建此链接,没有运行任何测试用例。您正在修改链接列表的标题,这是不应该做的。尝试获取另一个temp变量并将其分配给head。就像下面的代码
public void AddToIndex(int element, int index)
{
DNode temp = new DNode(element);
DNode temp1=Head;
for (int i = 1; i < index - 1; i++)
{
temp1 = temp1.next;
}
temp.next=temp1.next
temp1.next=temp
}
public void AddToIndex(int元素,int索引)
{
DNode温度=新的DNode(元件);
DNode temp1=头;
对于(int i=1;i
C#中已经存在数据类型,为什么要创建自己的实现?您正在更改head:head=head.next;您需要一个新的dnodexnode。然后在进入for循环之前设置xNode=Head。您需要保留循环中的前一个节点,以便将其下一个节点设置为新节点。此外,您似乎没有处理插入新磁头的情况。@MindSwipe我正在学习数据结构。请在调试器中单步执行您的代码,并在每一步检查变量的值。这将帮助您理解代码是如何工作的。如果您不知道如何使用调试器,现在是学习的最佳时机。这将为你节省无数个小时的挫折。
static class Program
{
static void Main(string[] args)
{
DLinkedList dLinked = new DLinkedList();
dLinked.AddToHead(5);
dLinked.AddToHead(7);
dLinked.AddToHead(10);
dLinked.AddToHead(11);
Console.WriteLine("---Add Head---");
dLinked.Display();
dLinked.AddToIndex(12, 4);
Console.WriteLine("---After AddToIndex function");
dLinked.Display();
}
}
public void AddToIndex(int element, int index)
{
DNode temp = new DNode(element);
DNode temp1=Head;
for (int i = 1; i < index - 1; i++)
{
temp1 = temp1.next;
}
temp.next=temp1.next
temp1.next=temp
}