【问题标题】:How to add an element at an index in singly linked list in C#如何在 C# 中的单链表中的索引处添加元素
【发布时间】:2019-08-22 12:04:55
【问题描述】:

我正在 C# 中实现链表数据结构。我面临以下问题。

当我尝试在单链表的索引处添加元素时,它不起作用。

下面是我的代码。问题在于函数 AddToIndex。它无法正常工作。

节点

public class DNode
{
    public int data;
    public DNode next;
    public DNode(int d)
    {
        data = d;
    }
}

链表

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;
        }
    }
}

显示结果集

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();

    }
}

控制台结果: ---添加头--- 11 10 7 5 ---调用 AddToIndex 函数后 -- 7 12 5

注意:我只是在构建这个,没有运行任何测试用例。

【问题讨论】:

  • LinkedList<T> C# 中已经存在数据类型,为什么要创建自己的实现?
  • 你正在改变头部:Head = Head.next;您需要一个新的 DNode xNode。然后在进入 for 循环之前设置 xNode = Head。
  • 您需要保留循环中的前一个节点,以便将其下一个节点设置为新节点。此外,您似乎没有处理插入新头的情况。
  • @MindSwipe 我正在学习数据结构。
  • 在调试器中单步执行您的代码,并在每一步检查变量的值。这将帮助您了解代码的工作原理。如果您不知道如何使用调试器,那么现在是学习的最佳时机。它将为您节省无数小时的挫败感。

标签: c# data-structures linked-list singly-linked-list


【解决方案1】:

您正在修改链表的头部,不应该这样做。尝试获取另一个临时变量并将其分配给 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            
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-13
    • 2012-07-21
    • 1970-01-01
    相关资源
    最近更新 更多