fr0stn1k

Правленные таски Ковылов

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