Интерфейс IEnumerable на списке - C#

Узнай цену своей работы

Формулировка задачи:

помогите реализовать интерфейс IEnumerable на моем списке не могу понять как правильно его сделать вот то что у меня есть
Листинг программы
  1. //1. реализовать интерфейс IEnumerable для своей реализации двусвязного списка.
  2. using System;
  3. using System.IO;
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. public class Node
  8. {
  9. private object _Data;
  10. private Node _Next;
  11. private Node _Prev;
  12. public object Value
  13. {
  14. get { return _Data; }
  15. set { _Data = value; }
  16. }
  17. public Node(object Data)
  18. {
  19. this._Data = Data;
  20. }
  21. public Node Next
  22. {
  23. get { return this._Next; }
  24. set { this._Next = value; }
  25. }
  26. public Node Prev
  27. {
  28. get { return this._Prev; }
  29. set { this._Prev = value; }
  30. }
  31. }
  32. public class Doubly_Linked_List : IEnumerable
  33. {
  34. private Node First;
  35. private Node Current;
  36. private Node Last;
  37. public uint size;
  38. public Doubly_Linked_List()
  39. {
  40. size = 0;
  41. First = Current = Last = null;
  42. }
  43. public bool isEmpty //проверка на пустоту
  44. {
  45. get
  46. {
  47. return size == 0;
  48. }
  49. }
  50. public void Insert_Index(object newElement, uint index) //вставить по индекусу
  51. {
  52. if (index < 1 || index > size) //вброс ошибки, если неправильный индекс
  53. {
  54. throw new InvalidOperationException();
  55. }
  56. else if (index == 1) //если начало
  57. {
  58. Push_Front(newElement);
  59. }
  60. else if (index == size) //если конец
  61. {
  62. Push_Back(newElement);
  63. }
  64. else //иначе ищем элемент с таким индексом
  65. {
  66. uint count = 1;
  67. Current = First;
  68. while (Current != null && count != index)
  69. {
  70. Current = Current.Next;
  71. count++;
  72. }
  73. Node newNode = new Node(newElement); //создаем объект
  74. Current.Prev.Next = newNode;
  75. newNode.Prev = Current.Prev;
  76. Current.Prev = newNode;
  77. newNode.Next = Current;
  78. }
  79. }
  80. public void Push_Front(object newElement)
  81. {
  82. Node newNode = new Node(newElement);
  83. if (First == null)
  84. {
  85. First = Last = newNode;
  86. }
  87. else
  88. {
  89. newNode.Next = First;
  90. First = newNode; //First и newNode указывают на один и тот же объект
  91. newNode.Next.Prev = First;
  92. }
  93. Count++;
  94. }
  95. public Node Pop_Front()
  96. {
  97. if (First == null)
  98. {
  99. throw new InvalidOperationException();
  100. }
  101. else
  102. {
  103. Node temp = First;
  104. if (First.Next != null)
  105. {
  106. First.Next.Prev = null;
  107. }
  108. First = First.Next;
  109. Count--;
  110. return temp;
  111. }
  112. }
  113. public void Push_Back(object newElement)
  114. {
  115. Node newNode = new Node(newElement);
  116. if (First == null)
  117. {
  118. First = Last = newNode;
  119. }
  120. else
  121. {
  122. Last.Next = newNode;
  123. newNode.Prev = Last;
  124. Last = newNode;
  125. }
  126. Count++;
  127. }
  128. public Node Pop_Back()
  129. {
  130. if (Last == null)
  131. {
  132. throw new InvalidOperationException();
  133. }
  134. else
  135. {
  136. Node temp = Last;
  137. if (Last.Prev != null)
  138. {
  139. Last.Prev.Next = null;
  140. }
  141. Last = Last.Prev;
  142. Count--;
  143. return temp;
  144. }
  145. }
  146. public void ClearList() //полностью очистить список
  147. {
  148. while (!isEmpty)
  149. {
  150. Pop_Front();
  151. }
  152. }
  153. public uint Count //свойство для size
  154. {
  155. get { return size; }
  156. set { size = value; }
  157. }
  158. public void Display() //вывести в прямом порядке
  159. {
  160. if (First == null)
  161. {
  162. Console.WriteLine("Doubly Linked List is empty");
  163. return;
  164. }
  165. Current = First;
  166. uint count = 1;
  167. while (Current != null)
  168. {
  169. Console.Write(Current.Value.ToString() + ", ");
  170. count++;
  171. Current = Current.Next;
  172. }
  173. }
  174. public void ReverseDisplay() //вывести в обратном порядке
  175. {
  176. if (Last == null)
  177. {
  178. Console.WriteLine("Doubly Linked List is empty");
  179. return;
  180. }
  181. Current = Last;
  182. uint count = 1;
  183. while (Current != null)
  184. {
  185. Console.Write(/*"Element " + count.ToString() + " : " +*/ Current.Value.ToString() + ", ");
  186. count++;
  187. Current = Current.Prev;
  188. }
  189. }
  190. //удалить элемент по индексу
  191. public void DeleteElement(uint index)
  192. {
  193. if (index < 1 || index > size)
  194. {
  195. throw new InvalidOperationException();
  196. }
  197. else if (index == 1)
  198. {
  199. Pop_Front();
  200. }
  201. else if (index == size)
  202. {
  203. Pop_Back();
  204. }
  205. else
  206. {
  207. uint count = 1;
  208. Current = First;
  209. while (Current != null && count != index)
  210. {
  211. Current = Current.Next;
  212. count++;
  213. }
  214. Current.Prev.Next = Current.Next;
  215. Current.Next.Prev = Current.Prev;
  216. }
  217. }
  218. public Node FindNode(object Data) //найти Node и вернуть его
  219. {
  220. Current = First;
  221. while (Current != null)
  222. {
  223. Current = Current.Next;
  224. }
  225. return Current;
  226. }
  227. public uint GetIndex(object Data) //достать индекс по значению элемента
  228. {
  229. Current = First;
  230. uint index = 1;
  231. while (Current != null)
  232. {
  233. Current = Current.Next;
  234. index++;
  235. }
  236. return index;
  237. }
  238. IEnumerator IEnumerable.GetEnumerator()
  239. {
  240. return (IEnumerator)GetEnumerator();
  241. }
  242. public PeopleEnum GetEnumerator()
  243. {
  244. return new PeopleEnum(Current.Value);
  245. }
  246. }
  247. public class PeopleEnum : IEnumerator
  248. {
  249. int position = -1;
  250. private Doubly_Linked_List value;
  251. private Node d;
  252. private object value1;
  253. public PeopleEnum(Doubly_Linked_List list)
  254. {
  255. value = list;
  256. }
  257. public PeopleEnum(Node value)
  258. {
  259. this.d = value;
  260. }
  261. public PeopleEnum(object value1)
  262. {
  263. this.value1 = value1;
  264. }
  265. public bool MoveNext()
  266. {
  267. position++;
  268. return (position < value.Count);
  269. }
  270. public void Reset()
  271. {
  272. position = -1;
  273. }
  274. public Doubly_Linked_List Current
  275. {
  276. get { return this.value; }
  277. }
  278. object IEnumerator.Current
  279. {
  280. get
  281. {
  282. if (this.position == 0 || this.position == this.value.size + 1)
  283. throw new InvalidOperationException();
  284. return (object)this.Current;
  285. }
  286. }
  287. }
  288.  
  289. class Program
  290. {
  291. static void Main()
  292. {
  293. Doubly_Linked_List list = new Doubly_Linked_List();
  294. ////проверка на пустоту
  295. Console.WriteLine(list.isEmpty);
  296. //добавить элемент в начало список
  297. list.Push_Front(12);
  298. list.Push_Front("WERTY");
  299. list.Push_Front("cos");
  300. list.Push_Front(3.3);
  301. //вывести в прямом порядке
  302. list.Display(); Console.WriteLine();
  303. Console.WriteLine(list.isEmpty);
  304. //вставить по индекусу
  305. list.Insert_Index(1.23, 3);
  306. list.Display(); Console.WriteLine();
  307. //удалить элемент с начала списка
  308. list.Pop_Front();
  309. list.Display(); Console.WriteLine();
  310. //добавить элемент в конец списка
  311. list.Push_Back(5); list.Display(); Console.WriteLine();
  312. //удалить элемент с конца списка
  313. list.Pop_Back(); list.Display(); Console.WriteLine();
  314. Console.WriteLine(list.Count);
  315. //list.ClearList();
  316. //Console.WriteLine(list.Count);
  317. //вывести в обратном порядке
  318. list.ReverseDisplay(); Console.WriteLine();
  319. //удалить элемент по индексу
  320. list.DeleteElement(1);
  321. list.Display(); Console.WriteLine();
  322. //найти Node и вернуть его
  323. Console.WriteLine(list.FindNode(22));
  324. //достать индекс по значению элемента
  325. Console.WriteLine(list.GetIndex(12)-1);
  326. Console.WriteLine();
  327. foreach (Doubly_Linked_List order in list)
  328. {
  329. Console.Write(order + ", ");
  330. }
  331. }
  332. }

Решение задачи: «Интерфейс IEnumerable на списке»

textual
Листинг программы
  1. //2. реализовать интерфейс IEnumerable для своей реализации бинарного дерева.
  2.  
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Collections;
  6. using System.Linq;
  7. using System.Text;
  8.  
  9. namespace ConsoleApplication1
  10. {
  11.     public class Tree : IEnumerable
  12.     {
  13.         private string value;
  14.         private int count;
  15.         private Tree left;
  16.         private Tree right;
  17.         // вставка
  18.         public void Insert(string value)
  19.         {
  20.  
  21.  
  22.             if (this.value == null)
  23.                 this.value = value;
  24.             else
  25.             {
  26.                 if (this.value.CompareTo(value) == 1)
  27.                 {
  28.                     if (left == null)
  29.                         this.left = new Tree();
  30.                     left.Insert(value);
  31.                 }
  32.                 else if (this.value.CompareTo(value) == -1)
  33.                 {
  34.                     if (right == null)
  35.                         this.right = new Tree();
  36.                     right.Insert(value);
  37.                 }
  38.                 else
  39.                     throw new Exception("Узел уже существует");
  40.             }
  41.  
  42.             this.count = Recount(this);
  43.         }
  44.         // поиск
  45.         public Tree Search(string value)
  46.         {
  47.  
  48.  
  49.             if (this.value == value)
  50.                 return this;
  51.             else if (this.value.CompareTo(value) == 1)
  52.             {
  53.                 if (left != null)
  54.                     return this.left.Search(value);
  55.                 else
  56.                     throw new Exception("Искомого узла в дереве нет");
  57.             }
  58.             else
  59.             {
  60.                 if (right != null)
  61.                     return this.right.Search(value);
  62.                 else
  63.                     throw new Exception("Искомого узла в дереве нет");
  64.             }
  65.         }
  66.         // отображение в строку
  67.         public string Display(Tree t)
  68.         {
  69.             string result = "";
  70.             if (t.left != null)
  71.                 result += Display(t.left);
  72.  
  73.             result += t.value + " ";
  74.  
  75.             if (t.right != null)
  76.                 result += Display(t.right);
  77.  
  78.             return result;
  79.         }
  80.         // подсчет
  81.         public int Recount(Tree t)
  82.         {
  83.             int count = 0;
  84.  
  85.             if (t.left != null)
  86.                 count += Recount(t.left);
  87.  
  88.             count++;
  89.  
  90.             if (t.right != null)
  91.                 count += Recount(t.right);
  92.  
  93.             return count;
  94.         }
  95.         // очистка
  96.         public void Clear()
  97.         {
  98.             this.value = null;
  99.             this.left = null;
  100.             this.right = null;
  101.         }
  102.         // проверка пустоты
  103.         public bool IsEmpty()
  104.         {
  105.             if (this.value == null)
  106.                 return true;
  107.             else
  108.                 return false;
  109.         }
  110.  
  111.         //удаление
  112.         public void Remove(string value)
  113.         {
  114.             Tree t = Search(value);
  115.             string[] str1 = Display(t).TrimEnd().Split(' ');
  116.             string[] str2 = new string[str1.Length - 1];
  117.  
  118.             int i = 0;
  119.             foreach (string s in str1)
  120.             {
  121.                 if (s != value)
  122.                     str2[i++] = s;
  123.             }
  124.  
  125.             t.Clear();
  126.             foreach (string s in str2)
  127.                 t.Insert(s);
  128.  
  129.             this.count = Recount(this);
  130.  
  131.  
  132.         }
  133.  
  134.         IEnumerator IEnumerable.GetEnumerator()
  135.         {
  136.             return (IEnumerator)GetEnumerator();
  137.         }
  138.         public IEnumerator GetEnumerator()
  139.         {
  140.             return new PeopleEnum( );
  141.         }
  142.     }
  143.     public class PeopleEnum : IEnumerator
  144.     {
  145.         object IEnumerator.Current
  146.         {
  147.             get
  148.             {
  149.                 throw new NotImplementedException();
  150.             }
  151.         }
  152.  
  153.         bool IEnumerator.MoveNext()
  154.         {
  155.             throw new NotImplementedException();
  156.         }
  157.  
  158.         void IEnumerator.Reset()
  159.         {
  160.             throw new NotImplementedException();
  161.         }
  162.     }
  163.  
  164.  
  165.  
  166.  
  167.  
  168.     class Program
  169.     {
  170.         static void Main(string[] args)
  171.         {
  172.  
  173.             Tree t = new Tree();
  174.             // вставка
  175.             t.Insert("df");
  176.             t.Insert("1");
  177.             t.Insert("2");
  178.             t.Insert("3");
  179.             t.Insert("яблоко");
  180.             t.Insert("saw");
  181.             Console.WriteLine(t.Display(t));
  182.             //удаление
  183.             t.Remove("яблоко");
  184.             Console.WriteLine(t.Display(t));
  185.             // подсчет
  186.             Console.WriteLine(t.Recount(t));
  187.             t.Clear();
  188.             Console.WriteLine(t.IsEmpty());
  189.             t.Insert("df");
  190.             t.Insert("1");
  191.             t.Insert("2");
  192.             Console.WriteLine(t.Display(t));
  193.  
  194.  
  195.             foreach (var test in t)
  196.                 Console.WriteLine(test + ", ");
  197.  
  198.         }
  199.     }
  200. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

5   голосов , оценка 4 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы