简体   繁体   中英

How to add an element at an index in singly linked list in C#

I am implementing linked-list data-structure in C#. I am facing below issue.

When I am try to add element at an index in singly linked list then it not working.

below is my code. Issue is in function AddToIndex. It is not working properly.

Node

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

LinkedList

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

To display result set

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

    }
}

Result on Console: ---Add Head--- 11 10 7 5 ---After AddToIndex function Called -- 7 12 5

Note: I am just building this no test cases is run .

you are modifying the head of the linked list, which should not be done. try taking another temp variable and assign it to head. like the code below.

       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            
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM