Home Ask Login Register

Developers Planet

Your answer is one click away!

Vitaliy February 2016

Remove from single linked list via index

How to make insert to generic linked list via index without using tail.

public void RemoveByIndex(int index)
{
    int count = 0;
    LinkedListNode<T> current = Head;
    while (count <= index)
    {
        if (count == index)
        {
            current.Next = null;
        }
        else
        {
            current = current.Next;
        }
        count++;
    }
    Head = current;
}

I've int list array with data 5, 10, 15. And I don't know why it always remove me 5,15 when I given him the 1'st index.

Answers


IsaacBok February 2016

var list1 = new LinkedList<int>();

var nodesToRemove = list1.Where(x => x == index).ToList();

foreach(var node in nodesToRemove)
        lis1.Remove(node);


Guy Levy February 2016

First iteration (count = 0) => else block is executed => current = current.next => current = 10, current.next = 15

Second iteration (count=1) => if block is executed => current.next = null => 15 is removed => current = 10

At the end of second iteration count = 2 and you exit the while loop => Head = current => Head = 10 => 5 is removed

possible solution:

public void RemoveByIndex(int index)
{
   int count = 0;
   LinkedListNode<T> current = Head;
   LinkedListNode<T> previous = current;
   while (count <= index)
   {
       if (count == index)
       {
           previous.next = current.next               
           current = null;               
       }
       else
       {
           previous = current;
           current = current.Next;
       }           
       count++;
   }       
} 

Post Status

Asked in February 2016
Viewed 1,019 times
Voted 14
Answered 2 times

Search




Leave an answer


Quote of the day: live life