Bird
Raised Fist0

Given a LinkedList<int> with values 1, 2, 3, 4, 5, which code snippet correctly removes all even numbers from the list?

hard🚀 Application Q15 of Q15
C Sharp (C#) - Collections
Given a LinkedList<int> with values 1, 2, 3, 4, 5, which code snippet correctly removes all even numbers from the list?
Aforeach(var node in list) { if(node % 2 == 0) list.Remove(node); }
Bfor(int i = 0; i < list.Count; i++) { if(list.ElementAt(i) % 2 == 0) list.Remove(list.ElementAt(i)); }
Cvar current = list.First; while(current != null) { var next = current.Next; if(current.Value % 2 == 0) list.Remove(current); current = next; }
Dlist.RemoveAll(x => x % 2 == 0);
Step-by-Step Solution
Solution:
  1. Step 1: Understand safe removal during iteration

    Removing nodes while iterating requires storing next node before removal to avoid invalid references.
  2. Step 2: Analyze each option

    foreach(var node in list) { if(node % 2 == 0) list.Remove(node); } uses foreach which throws error on modification during iteration. var current = list.First; while(current != null) { var next = current.Next; if(current.Value % 2 == 0) list.Remove(current); current = next; } correctly uses a while loop with next node saved. for(int i = 0; i < list.Count; i++) { if(list.ElementAt(i) % 2 == 0) list.Remove(list.ElementAt(i)); } uses ElementAt which is inefficient and unsafe. list.RemoveAll(x => x % 2 == 0); is invalid as LinkedList has no RemoveAll method.
  3. Final Answer:

    var current = list.First; while(current != null) { var next = current.Next; if(current.Value % 2 == 0) list.Remove(current); current = next; } -> Option C
  4. Quick Check:

    Use while loop with next saved to remove nodes safely [OK]
Quick Trick: Save next node before removal to avoid iteration errors. [OK]
Common Mistakes:
MISTAKES
  • Modifying list inside foreach causes runtime error
  • Using RemoveAll which LinkedList does not have
  • Using ElementAt which is inefficient and unsafe

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More C Sharp (C#) Quizzes