Интерфейс IEnumerable на списке - C#
Формулировка задачи:
помогите реализовать интерфейс IEnumerable на моем списке
не могу понять как правильно его сделать
вот то что у меня есть
Листинг программы
- //1. реализовать интерфейс IEnumerable для своей реализации двусвязного списка.
- using System;
- using System.IO;
- using System.Collections;
- using System.Collections.Generic;
- using System.Linq;
- public class Node
- {
- private object _Data;
- private Node _Next;
- private Node _Prev;
- public object Value
- {
- get { return _Data; }
- set { _Data = value; }
- }
- public Node(object Data)
- {
- this._Data = Data;
- }
- public Node Next
- {
- get { return this._Next; }
- set { this._Next = value; }
- }
- public Node Prev
- {
- get { return this._Prev; }
- set { this._Prev = value; }
- }
- }
- public class Doubly_Linked_List : IEnumerable
- {
- private Node First;
- private Node Current;
- private Node Last;
- public uint size;
- public Doubly_Linked_List()
- {
- size = 0;
- First = Current = Last = null;
- }
- public bool isEmpty //проверка на пустоту
- {
- get
- {
- return size == 0;
- }
- }
- public void Insert_Index(object newElement, uint index) //вставить по индекусу
- {
- if (index < 1 || index > size) //вброс ошибки, если неправильный индекс
- {
- throw new InvalidOperationException();
- }
- else if (index == 1) //если начало
- {
- Push_Front(newElement);
- }
- else if (index == size) //если конец
- {
- Push_Back(newElement);
- }
- else //иначе ищем элемент с таким индексом
- {
- uint count = 1;
- Current = First;
- while (Current != null && count != index)
- {
- Current = Current.Next;
- count++;
- }
- Node newNode = new Node(newElement); //создаем объект
- Current.Prev.Next = newNode;
- newNode.Prev = Current.Prev;
- Current.Prev = newNode;
- newNode.Next = Current;
- }
- }
- public void Push_Front(object newElement)
- {
- Node newNode = new Node(newElement);
- if (First == null)
- {
- First = Last = newNode;
- }
- else
- {
- newNode.Next = First;
- First = newNode; //First и newNode указывают на один и тот же объект
- newNode.Next.Prev = First;
- }
- Count++;
- }
- public Node Pop_Front()
- {
- if (First == null)
- {
- throw new InvalidOperationException();
- }
- else
- {
- Node temp = First;
- if (First.Next != null)
- {
- First.Next.Prev = null;
- }
- First = First.Next;
- Count--;
- return temp;
- }
- }
- public void Push_Back(object newElement)
- {
- Node newNode = new Node(newElement);
- if (First == null)
- {
- First = Last = newNode;
- }
- else
- {
- Last.Next = newNode;
- newNode.Prev = Last;
- Last = newNode;
- }
- Count++;
- }
- public Node Pop_Back()
- {
- if (Last == null)
- {
- throw new InvalidOperationException();
- }
- else
- {
- Node temp = Last;
- if (Last.Prev != null)
- {
- Last.Prev.Next = null;
- }
- Last = Last.Prev;
- Count--;
- return temp;
- }
- }
- public void ClearList() //полностью очистить список
- {
- while (!isEmpty)
- {
- Pop_Front();
- }
- }
- public uint Count //свойство для size
- {
- get { return size; }
- set { size = value; }
- }
- public void Display() //вывести в прямом порядке
- {
- if (First == null)
- {
- Console.WriteLine("Doubly Linked List is empty");
- return;
- }
- Current = First;
- uint count = 1;
- while (Current != null)
- {
- Console.Write(Current.Value.ToString() + ", ");
- count++;
- Current = Current.Next;
- }
- }
- public void ReverseDisplay() //вывести в обратном порядке
- {
- if (Last == null)
- {
- Console.WriteLine("Doubly Linked List is empty");
- return;
- }
- Current = Last;
- uint count = 1;
- while (Current != null)
- {
- Console.Write(/*"Element " + count.ToString() + " : " +*/ Current.Value.ToString() + ", ");
- count++;
- Current = Current.Prev;
- }
- }
- //удалить элемент по индексу
- public void DeleteElement(uint index)
- {
- if (index < 1 || index > size)
- {
- throw new InvalidOperationException();
- }
- else if (index == 1)
- {
- Pop_Front();
- }
- else if (index == size)
- {
- Pop_Back();
- }
- else
- {
- uint count = 1;
- Current = First;
- while (Current != null && count != index)
- {
- Current = Current.Next;
- count++;
- }
- Current.Prev.Next = Current.Next;
- Current.Next.Prev = Current.Prev;
- }
- }
- public Node FindNode(object Data) //найти Node и вернуть его
- {
- Current = First;
- while (Current != null)
- {
- Current = Current.Next;
- }
- return Current;
- }
- public uint GetIndex(object Data) //достать индекс по значению элемента
- {
- Current = First;
- uint index = 1;
- while (Current != null)
- {
- Current = Current.Next;
- index++;
- }
- return index;
- }
- IEnumerator IEnumerable.GetEnumerator()
- {
- return (IEnumerator)GetEnumerator();
- }
- public PeopleEnum GetEnumerator()
- {
- return new PeopleEnum(Current.Value);
- }
- }
- public class PeopleEnum : IEnumerator
- {
- int position = -1;
- private Doubly_Linked_List value;
- private Node d;
- private object value1;
- public PeopleEnum(Doubly_Linked_List list)
- {
- value = list;
- }
- public PeopleEnum(Node value)
- {
- this.d = value;
- }
- public PeopleEnum(object value1)
- {
- this.value1 = value1;
- }
- public bool MoveNext()
- {
- position++;
- return (position < value.Count);
- }
- public void Reset()
- {
- position = -1;
- }
- public Doubly_Linked_List Current
- {
- get { return this.value; }
- }
- object IEnumerator.Current
- {
- get
- {
- if (this.position == 0 || this.position == this.value.size + 1)
- throw new InvalidOperationException();
- return (object)this.Current;
- }
- }
- }
- class Program
- {
- static void Main()
- {
- Doubly_Linked_List list = new Doubly_Linked_List();
- ////проверка на пустоту
- Console.WriteLine(list.isEmpty);
- //добавить элемент в начало список
- list.Push_Front(12);
- list.Push_Front("WERTY");
- list.Push_Front("cos");
- list.Push_Front(3.3);
- //вывести в прямом порядке
- list.Display(); Console.WriteLine();
- Console.WriteLine(list.isEmpty);
- //вставить по индекусу
- list.Insert_Index(1.23, 3);
- list.Display(); Console.WriteLine();
- //удалить элемент с начала списка
- list.Pop_Front();
- list.Display(); Console.WriteLine();
- //добавить элемент в конец списка
- list.Push_Back(5); list.Display(); Console.WriteLine();
- //удалить элемент с конца списка
- list.Pop_Back(); list.Display(); Console.WriteLine();
- Console.WriteLine(list.Count);
- //list.ClearList();
- //Console.WriteLine(list.Count);
- //вывести в обратном порядке
- list.ReverseDisplay(); Console.WriteLine();
- //удалить элемент по индексу
- list.DeleteElement(1);
- list.Display(); Console.WriteLine();
- //найти Node и вернуть его
- Console.WriteLine(list.FindNode(22));
- //достать индекс по значению элемента
- Console.WriteLine(list.GetIndex(12)-1);
- Console.WriteLine();
- foreach (Doubly_Linked_List order in list)
- {
- Console.Write(order + ", ");
- }
- }
- }
Решение задачи: «Интерфейс IEnumerable на списке»
textual
Листинг программы
- //2. реализовать интерфейс IEnumerable для своей реализации бинарного дерева.
- using System;
- using System.Collections.Generic;
- using System.Collections;
- using System.Linq;
- using System.Text;
- namespace ConsoleApplication1
- {
- public class Tree : IEnumerable
- {
- private string value;
- private int count;
- private Tree left;
- private Tree right;
- // вставка
- public void Insert(string value)
- {
- if (this.value == null)
- this.value = value;
- else
- {
- if (this.value.CompareTo(value) == 1)
- {
- if (left == null)
- this.left = new Tree();
- left.Insert(value);
- }
- else if (this.value.CompareTo(value) == -1)
- {
- if (right == null)
- this.right = new Tree();
- right.Insert(value);
- }
- else
- throw new Exception("Узел уже существует");
- }
- this.count = Recount(this);
- }
- // поиск
- public Tree Search(string value)
- {
- if (this.value == value)
- return this;
- else if (this.value.CompareTo(value) == 1)
- {
- if (left != null)
- return this.left.Search(value);
- else
- throw new Exception("Искомого узла в дереве нет");
- }
- else
- {
- if (right != null)
- return this.right.Search(value);
- else
- throw new Exception("Искомого узла в дереве нет");
- }
- }
- // отображение в строку
- public string Display(Tree t)
- {
- string result = "";
- if (t.left != null)
- result += Display(t.left);
- result += t.value + " ";
- if (t.right != null)
- result += Display(t.right);
- return result;
- }
- // подсчет
- public int Recount(Tree t)
- {
- int count = 0;
- if (t.left != null)
- count += Recount(t.left);
- count++;
- if (t.right != null)
- count += Recount(t.right);
- return count;
- }
- // очистка
- public void Clear()
- {
- this.value = null;
- this.left = null;
- this.right = null;
- }
- // проверка пустоты
- public bool IsEmpty()
- {
- if (this.value == null)
- return true;
- else
- return false;
- }
- //удаление
- public void Remove(string value)
- {
- Tree t = Search(value);
- string[] str1 = Display(t).TrimEnd().Split(' ');
- string[] str2 = new string[str1.Length - 1];
- int i = 0;
- foreach (string s in str1)
- {
- if (s != value)
- str2[i++] = s;
- }
- t.Clear();
- foreach (string s in str2)
- t.Insert(s);
- this.count = Recount(this);
- }
- IEnumerator IEnumerable.GetEnumerator()
- {
- return (IEnumerator)GetEnumerator();
- }
- public IEnumerator GetEnumerator()
- {
- return new PeopleEnum( );
- }
- }
- public class PeopleEnum : IEnumerator
- {
- object IEnumerator.Current
- {
- get
- {
- throw new NotImplementedException();
- }
- }
- bool IEnumerator.MoveNext()
- {
- throw new NotImplementedException();
- }
- void IEnumerator.Reset()
- {
- throw new NotImplementedException();
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- Tree t = new Tree();
- // вставка
- t.Insert("df");
- t.Insert("1");
- t.Insert("2");
- t.Insert("3");
- t.Insert("яблоко");
- t.Insert("saw");
- Console.WriteLine(t.Display(t));
- //удаление
- t.Remove("яблоко");
- Console.WriteLine(t.Display(t));
- // подсчет
- Console.WriteLine(t.Recount(t));
- t.Clear();
- Console.WriteLine(t.IsEmpty());
- t.Insert("df");
- t.Insert("1");
- t.Insert("2");
- Console.WriteLine(t.Display(t));
- foreach (var test in t)
- Console.WriteLine(test + ", ");
- }
- }
- }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д