C# get value from a LinkedList

Viewed 61

I'm currently working in a program which contains a class named LinkedList. It uses nodes to create the functions Add at beginning, Insert At Position, Get Info at position and Eliminate at position. I'm having trouble with the Get function because it's not getting the correct value from the list and I don't know exaclty why.

The definition for Node in the program is:

        public class Node<T>
    {
        public T value;
        public Node<T> next;
    }

The code for the Get function is:

        public T Get(int index)
    {
        if (start == null)
        {
            throw new Exception("Nothing to show");
        }
        if (index == 0)
        {
            return start.value;
        }
        Node<T> previous = start;
        for (int i = 0; i < index; i++)
        {
            previous = previous.next;
        }

        return previous.value;
    }

Also, I have these tests where my code is failing when the Get is used. The lists are created when the class LinkedList is used an then, it uses his attributes to invoke the Add, Get, AddAt and Eliminate functions in the tests.

        [Test]
    public void AddMultipleThenGetAll ()
    {
        LinkedList<int> linkedList = new LinkedList<int>();
        linkedList.Add(42);
        linkedList.Add(43);
        linkedList.Add(44);

        int[] results = new int[] { 42, 43, 44 };
        for (int i = 0; i < results.Length; i++)
        {
            if (linkedList.Get(i) != results[i])
                Assert.Fail();
        }
        Assert.Pass();
    }

        [Test]
    public void AddMultipleAndRemoveInTheMiddle()
    {
        LinkedList<int> linkedList = new LinkedList<int>();
        linkedList.Add(42);
        linkedList.Add(43);
        linkedList.Add(44);
        linkedList.Remove(1);

        Console.WriteLine(linkedList);
        Assert.AreEqual(44, linkedList.Get(1));
    }

The rest of functions are working properly.

1 Answers

Your for loop in your get method has a bug. You are looping all the way to your desired index then setting previous to the next item, which doesn't exist or it isn't the index / item you want. Try this instead.

Node<T> previous = start;
for (int i = 0; i < index - 1; i++)
{
     previous = previous.next;
}
return previous.value;
Related