fr0stn1k

Все таски

Jul 11th, 2018
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 10.40 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4.  
  5. namespace CSHARPMEDIUM
  6. {
  7.     class Program
  8.     {
  9.         static void Main(string[] args)
  10.         {
  11.             LinkedList<int> list = new LinkedList<int>();
  12.             list.Add(10);
  13.             list.Add(15);
  14.             list.Add(20);
  15.             // Test of Contains() of LinkedList
  16.             Console.WriteLine("Тест метода Contains()");
  17.             var answer = (list.Contains(list._start, 20)) ? "Содержит" : "Не содержит";
  18.             Console.WriteLine($"Содержит ли лист элемент 20?\nОтвет: {answer}");
  19.             answer = (list.Contains(list._start, 30)) ? "Содержит" : "Не содержит";
  20.             Console.WriteLine($"Содержит ли лист элемент 30?\nОтвет: {answer}");
  21.             Console.WriteLine();
  22.  
  23.             // Test of RemoveAt() of LinkedList
  24.             Console.WriteLine("Тест метода RemoveAt()");
  25.             Console.WriteLine("Изначальные элементы:");
  26.             list.ForEach(Console.WriteLine);
  27.             Console.WriteLine($"Количество элементов: {list.Count}\n");
  28.  
  29.             // Удаляем второй элемент
  30.             list.RemoveAt(1);
  31.             Console.WriteLine("После удаления второго элемента:");
  32.             list.ForEach(Console.WriteLine);
  33.             Console.WriteLine($"Количество элементов: {list.Count}\n");
  34.  
  35.  
  36.             // Test of IEnumerable
  37.             Console.WriteLine("Тест IEnumerable");
  38.             Book myLib = new Book("Книга с книгами");
  39.             Book b1 = new Book("Blood, sweat and Pixels");
  40.             Book b2 = new Book("C#4.0");
  41.             b1.Parent = myLib;
  42.             b2.Parent = myLib;
  43.  
  44.             foreach (Book item in myLib)
  45.             {
  46.                 Console.WriteLine($"Book: {item.Name}");
  47.             }
  48.             Console.WriteLine();
  49.  
  50.  
  51.             Console.WriteLine("Тест стека");
  52.             Stack<string> strings = new Stack<string>();
  53.             strings.Push("Test1");
  54.             strings.Push("Test2");
  55.             strings.Push("Test3");
  56.             strings.Push("Test4");
  57.             Console.WriteLine(strings.Pop());
  58.             Console.WriteLine(strings.Pop());
  59.             Console.WriteLine(strings.Pop());
  60.             Console.WriteLine();
  61.  
  62.             Console.WriteLine("Тест очереди");
  63.             Queue<string> strings2 = new Queue<string>();
  64.             strings2.Enqueue("Test1");
  65.             strings2.Enqueue("Test2");
  66.             strings2.Enqueue("Test3");
  67.             strings2.Enqueue("Test4");
  68.             Console.WriteLine(strings2.Dequeue());
  69.             Console.WriteLine(strings2.Dequeue());
  70.             Console.WriteLine(strings2.Dequeue());
  71.  
  72.  
  73.  
  74.  
  75.         }
  76.     }
  77.  
  78.     //Задача 1: Сделать реализацию IEnumerable
  79.  
  80.     class Book : IEnumerable<Book>
  81.     {
  82.         public static List<Book> Library = new List<Book>();
  83.         public Book Parent;
  84.         public string Name;
  85.  
  86.         public Book(string name)
  87.         {
  88.             Library.Add(this);
  89.             Name = name;
  90.         }
  91.  
  92.         public IEnumerator<Book> GetEnumerator()
  93.         {
  94.             return new LibraryEnumerator(Library.FindAll((b) => b.Parent == this).ToArray());
  95.         }
  96.  
  97.         IEnumerator IEnumerable.GetEnumerator()
  98.         {
  99.             return GetEnumerator();
  100.         }
  101.     }
  102.  
  103.     class LibraryEnumerator : IEnumerator<Book>
  104.     {
  105.         public Book Current => _elements[_current];
  106.         private Book[] _elements;
  107.         private int _current = -1;
  108.         object IEnumerator.Current => Current;
  109.  
  110.         public LibraryEnumerator(Book[] elements)
  111.         {
  112.             _elements = elements;
  113.         }
  114.  
  115.         public void Dispose()
  116.         {
  117.             _elements = null;
  118.         }
  119.  
  120.         public bool MoveNext()
  121.         {
  122.             _current++;
  123.             return _current < _elements.Length;
  124.         }
  125.  
  126.         public void Reset()
  127.         {
  128.             _current = -1;
  129.         }
  130.     }
  131.  
  132.  
  133.     //Задача 2: Сделать метод Contains. Проверяет есть ли заданное значенеи в спике
  134.     //Задача 3: Сделать метод Remove, который удаляет эллемент под каким-либо номером
  135.     //Задача 4: Оптимизировать добавление эллемента, через хранение ссылки на конец списка
  136.     class LinkedList<T>
  137.     {
  138.         public ListElement _start;
  139.  
  140.         public int Count
  141.         {
  142.             get
  143.             {
  144.                 int count = 0;
  145.                 ForEach((x) => count++);
  146.                 return count;
  147.             }
  148.         }
  149.  
  150.         // Задача 2. Рекурсивный метод поиска элемента
  151.         public bool Contains(ListElement start, T element)
  152.         {
  153.             // Выход из рекурсии
  154.             if (start == null)
  155.                 return false;
  156.  
  157.             // Список содержит элемент
  158.             if (start.Data.Equals(element))
  159.                 return true;
  160.  
  161.             // Рекурсивный случай
  162.             return Contains(start.Next, element);
  163.         }
  164.  
  165.         // Задача 3. Удаление элемента
  166.         public void RemoveAt(int index)
  167.         {
  168.             // Лист пустой
  169.             if (_start == null)
  170.                 return;
  171.  
  172.             // Временное хранение стартового элемента
  173.             ListElement current = _start;
  174.  
  175.             // Если нужно удалить первый элемент
  176.             if (index == 0)
  177.             {
  178.                 _start = current.Next;
  179.                 return;
  180.             }
  181.  
  182.             // Поиск элемента идущего до удаляемого
  183.             for (var i = 0; current != null && i < index - 1; i++)
  184.                 current = current.Next;
  185.            
  186.             // Если индекс вне пределов списка
  187.             if (current == null || current.Next == null)
  188.                 return;
  189.            
  190.             // Элемент current.Next необходимый к удалению
  191.             // Записываем значение элемента идущего после удаляемого
  192.             ListElement nextAfterCurrent = current.Next.Next;
  193.  
  194.             // Удаляем элемент
  195.             current.Next = nextAfterCurrent;  
  196.            
  197.         }
  198.  
  199.         //Задача 4: Оптимизировать добавление эллемента, через хранение ссылки на конец списка
  200.         public void Add(T data)
  201.         {
  202.             var newElement = new ListElement(data);
  203.             ListElement endOfList = null;
  204.  
  205.             // Если список пуст
  206.             if (_start == null)
  207.             {
  208.                 _start = newElement;
  209.                 return;
  210.             }
  211.  
  212.             // Храним текущий элемент
  213.             ListElement current = _start;
  214.  
  215.             // Пока есть элементы, перебор
  216.             if (endOfList == null)
  217.             {
  218.                 while (current.Next != null)
  219.                 {
  220.                     current = current.Next;
  221.                 }
  222.                 endOfList = current;
  223.             }
  224.             else current = endOfList;
  225.  
  226.             // Добавление последнего элемента
  227.             current.Next = newElement;
  228.  
  229.             endOfList = current;
  230.  
  231.         }
  232.  
  233.         public void ForEach(Action<T> body)
  234.         {
  235.             ListElement current = _start;
  236.             while (current != null)
  237.             {
  238.                 body(current.Data);
  239.                 current = current.Next;
  240.             }
  241.         }
  242.  
  243.         public class ListElement
  244.         {
  245.             public static T StaticData;
  246.  
  247.             public T Data;
  248.             public ListElement Next;
  249.  
  250.             public ListElement(T data)
  251.             {
  252.                 Data = data;
  253.             }
  254.         }
  255.     }
  256.  
  257.     //Задача 5: сделать обобщённую очередь
  258.  
  259.     class Queue<T>
  260.     {
  261.         private QueueElement _head;
  262.         private QueueElement _tail;
  263.  
  264.         // Добавление элемента в очередь
  265.         public void Enqueue(T data)
  266.         {
  267.             var newElement = new QueueElement(data);
  268.  
  269.             if (_head == null)
  270.             {
  271.                 _head = newElement;
  272.                 _tail = _head;
  273.             }
  274.             else
  275.             {
  276.                 _tail.Next = newElement;
  277.                 _tail = _tail.Next;
  278.             }
  279.         }
  280.  
  281.         // Удаление элемента из очереди
  282.         public T Dequeue()
  283.         {
  284.             if (_head == null)
  285.             {
  286.                 throw new Exception("Очередь пуста");
  287.             }
  288.             var _result = _head.Data;
  289.             _head = _head.Next;
  290.             return _result;
  291.         }
  292.  
  293.         // Первый элемент
  294.         public T Peek()
  295.         {
  296.             return _head.Data;
  297.         }
  298.  
  299.         public class QueueElement
  300.         {
  301.             public T Data;
  302.             public QueueElement Next;
  303.  
  304.             public QueueElement(T data)
  305.             {
  306.                 Data = data;
  307.             }
  308.         }
  309.     }
  310.  
  311.     class Stack<T>
  312.     {
  313.         private StackElement _head;
  314.  
  315.         public void Push(T data)
  316.         {
  317.             var newElement = new StackElement(data);
  318.             newElement.Next = _head;
  319.             _head = newElement;
  320.         }
  321.  
  322.         public T Pop()
  323.         {
  324.             var h = _head;
  325.             _head = h.Next;
  326.             return h.Data;
  327.         }
  328.  
  329.         public T Peek()
  330.         {
  331.             return _head.Data;
  332.         }
  333.  
  334.         public Stack<T> Clone()
  335.         {
  336.             Stack<T> newStack = new Stack<T>();
  337.             newStack._head = _head;
  338.             return newStack;
  339.         }
  340.  
  341.         public class StackElement
  342.         {
  343.             public T Data;
  344.             public StackElement Next;
  345.  
  346.             public StackElement(T data)
  347.             {
  348.                 Data = data;
  349.             }
  350.         }
  351.     }
  352. }
Advertisement
Add Comment
Please, Sign In to add comment