Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a good way to iterate through a .NET LinkedList and remove elements?

Tags:

iterator

c#

.net

I'm thinking of doing the following:

for(LinkedListNode<MyClass> it = myCollection.First; it != null; it = it.Next)
{
    if(it.Value.removalCondition == true)
        it.Value = null;
}

What I'm wondering is: if simply pointing the it.Value to null actually gets rid of it.

like image 547
they changed my name Avatar asked Feb 28 '10 00:02

they changed my name


People also ask

What method is used to iterate through each element in a LinkedList?

The LinkedList. iterator() method returns an iterator over the sequence of elements of the Linked List in proper order.

Can you loop through a linked list?

An Iterator can be used to loop through an LinkedList. The method hasNext( ) returns true if there are more elements in LinkedList and false otherwise. The method next( ) returns the next element in the LinkedList and throws the exception NoSuchElementException if there is no next element.

Is LinkedList faster than list?

It depends on what you're trying to accomplish. If you want to search or access a specific element, arrays are faster, but if you want to insert or delete an element, a linked list is faster.

What is the best way to detect a cycle in a linked list?

You can make use of Floyd's cycle-finding algorithm, also known as tortoise and hare algorithm. The idea is to have two references to the list and move them at different speeds. Move one forward by 1 node and the other by 2 nodes. If the linked list has a loop they will definitely meet.


2 Answers

Setting the it.Value to null will not remove the node from the list Here is one way:

    for(LinkedListNode<MyClass> it = myCollection.First; it != null; )
    {
        LinkedListNode<MyClass> next = it.Next;
        if(it.Value.removalCondition == true)
              myCollection.Remove(it); // as a side effect it.Next == null

        it = next;
    }
like image 80
ILIA BROUDNO Avatar answered Oct 31 '22 04:10

ILIA BROUDNO


Surely (with a linked list) you need to change the link.

Eg, if you want to remove B from the LL A-B-C, you need to change A's link to B to C.

I'll admit I'm not familiar with the .NET implementation of linked lists but hopefully that's a start for you.

like image 45
Oli Avatar answered Oct 31 '22 03:10

Oli