Search code examples
c#data-structureslinked-listsingly-linked-list

Removing element from Linked List by index


I wrote a simple Linked List generic implementation, just for practice. Everything is working, but when I call RemoveByIndex(0), it does nothing, and I don't know why.

public void RemoveByIndex(int index)
    {
        int count = 0;
        Node<T> current = head;
        Node<T> previous = current;

        try
        {
            while (count < index)
            {
                previous = current;
                current = current.next;
                count++;
            }
            previous.next = current.next;
            current = null;
        }
        catch (NullReferenceException)
        {
            while (true)
            {
                Console.WriteLine($"Invalid index\nEnter valid index(int) in range 0 - {--count}");
                string input = Console.ReadLine();
                if(Int32.TryParse(input, out int inputI))
                {
                    RemoveByIndex(inputI);
                    break;
                }
                    
               
            }
            
        }

    }

Solution

  • When you call your method with index = 0 => your loop does not do anything because 0 < 0 is False => nothing

    You should do head = head.next if list contains 1 < elements, otherwise head = null, or simply change your loop condition