using System; using System.Collections.Generic; using System.IO; namespace ConsoleApplication { class Program { static void Main(string[] args) { Random rnd = new Random(123); LinkedList<int> list = new LinkedList<int>(); for (int i = 0; i < 25; i++) { list.AddLast(rnd.Next(0,5)); } //Берем итератор var iter = list.GetEnumerator(); Console.WriteLine("До:"); foreach (var i in list) { Console.WriteLine(i); } Console.WriteLine(); var el = list.First; while (iter.MoveNext()) { int prev = -9999; int next = -99; if (el.Previous != null) { prev = el.Previous.Value; } if (el.Next != null) { next = el.Next.Value; } if (el.Value == prev || prev == next || el.Value == next) { Console.WriteLine("DELETE: Prev:{0} ,Curr:{1}, Next:{2}", prev, el.Value, next); //Удаление элемента list.Remove(el); //Получение итератора нового списка iter = list.GetEnumerator(); el = list.First; } if (list.Count > 0 && el.Next != null) { el = el.Next; } } Console.WriteLine(); Console.WriteLine("После:"); foreach (var i in list) { Console.WriteLine(i); } Console.ReadKey(); } } }
Standard input is empty
До: 4 3 1 4 4 0 0 2 4 3 0 4 2 4 0 0 1 0 0 1 3 4 2 3 1 DELETE: Prev:1 ,Curr:4, Next:4 DELETE: Prev:4 ,Curr:0, Next:0 DELETE: Prev:4 ,Curr:2, Next:4 DELETE: Prev:0 ,Curr:4, Next:4 DELETE: Prev:0 ,Curr:4, Next:0 DELETE: Prev:3 ,Curr:0, Next:0 DELETE: Prev:3 ,Curr:0, Next:0 DELETE: Prev:0 ,Curr:1, Next:0 DELETE: Prev:3 ,Curr:0, Next:0 DELETE: Prev:3 ,Curr:0, Next:0 После: 4 3 1 4 0 2 4 3 0 1 3 4 2 3 1