Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections;
- using System.Collections.Generic;
- namespace CSHARPMEDIUM
- {
- class Program
- {
- static void Main(string[] args)
- {
- LinkedList<int> list = new LinkedList<int>();
- list.Add(10);
- list.Add(15);
- list.Add(20);
- // Test of Contains() of LinkedList
- Console.WriteLine("Тест метода Contains()");
- var answer = (list.Contains(list._start, 20)) ? "Содержит" : "Не содержит";
- Console.WriteLine($"Содержит ли лист элемент 20?\nОтвет: {answer}");
- answer = (list.Contains(list._start, 30)) ? "Содержит" : "Не содержит";
- Console.WriteLine($"Содержит ли лист элемент 30?\nОтвет: {answer}");
- Console.WriteLine();
- // Test of RemoveAt() of LinkedList
- Console.WriteLine("Тест метода RemoveAt()");
- Console.WriteLine("Изначальные элементы:");
- list.ForEach(Console.WriteLine);
- Console.WriteLine($"Количество элементов: {list.Count}\n");
- // Удаляем второй элемент
- list.RemoveAt(1);
- Console.WriteLine("После удаления второго элемента:");
- list.ForEach(Console.WriteLine);
- Console.WriteLine($"Количество элементов: {list.Count}\n");
- // Test of IEnumerable
- Console.WriteLine("Тест IEnumerable");
- Book myLib = new Book("Книга с книгами");
- Book b1 = new Book("Blood, sweat and Pixels");
- Book b2 = new Book("C#4.0");
- b1.Parent = myLib;
- b2.Parent = myLib;
- foreach (Book item in myLib)
- {
- Console.WriteLine($"Book: {item.Name}");
- }
- Console.WriteLine();
- Console.WriteLine("Тест стека");
- Stack<string> strings = new Stack<string>();
- strings.Push("Test1");
- strings.Push("Test2");
- strings.Push("Test3");
- strings.Push("Test4");
- Console.WriteLine(strings.Pop());
- Console.WriteLine(strings.Pop());
- Console.WriteLine(strings.Pop());
- Console.WriteLine();
- Console.WriteLine("Тест очереди");
- Queue<string> strings2 = new Queue<string>();
- strings2.Enqueue("Test1");
- strings2.Enqueue("Test2");
- strings2.Enqueue("Test3");
- strings2.Enqueue("Test4");
- Console.WriteLine(strings2.Dequeue());
- Console.WriteLine(strings2.Dequeue());
- Console.WriteLine(strings2.Dequeue());
- }
- }
- //Задача 1: Сделать реализацию IEnumerable
- class Book : IEnumerable<Book>
- {
- public static List<Book> Library = new List<Book>();
- public Book Parent;
- public string Name;
- public Book(string name)
- {
- Library.Add(this);
- Name = name;
- }
- public IEnumerator<Book> GetEnumerator()
- {
- return new LibraryEnumerator(Library.FindAll((b) => b.Parent == this).ToArray());
- }
- IEnumerator IEnumerable.GetEnumerator()
- {
- return GetEnumerator();
- }
- }
- class LibraryEnumerator : IEnumerator<Book>
- {
- public Book Current => _elements[_current];
- private Book[] _elements;
- private int _current = -1;
- object IEnumerator.Current => Current;
- public LibraryEnumerator(Book[] elements)
- {
- _elements = elements;
- }
- public void Dispose()
- {
- _elements = null;
- }
- public bool MoveNext()
- {
- _current++;
- return _current < _elements.Length;
- }
- public void Reset()
- {
- _current = -1;
- }
- }
- //Задача 2: Сделать метод Contains. Проверяет есть ли заданное значенеи в спике
- //Задача 3: Сделать метод Remove, который удаляет эллемент под каким-либо номером
- //Задача 4: Оптимизировать добавление эллемента, через хранение ссылки на конец списка
- class LinkedList<T>
- {
- public ListElement _start;
- public int Count
- {
- get
- {
- int count = 0;
- ForEach((x) => count++);
- return count;
- }
- }
- // Задача 2. Рекурсивный метод поиска элемента
- public bool Contains(ListElement start, T element)
- {
- // Выход из рекурсии
- if (start == null)
- return false;
- // Список содержит элемент
- if (start.Data.Equals(element))
- return true;
- // Рекурсивный случай
- return Contains(start.Next, element);
- }
- // Задача 3. Удаление элемента
- public void RemoveAt(int index)
- {
- // Лист пустой
- if (_start == null)
- return;
- // Временное хранение стартового элемента
- ListElement current = _start;
- // Если нужно удалить первый элемент
- if (index == 0)
- {
- _start = current.Next;
- return;
- }
- // Поиск элемента идущего до удаляемого
- for (var i = 0; current != null && i < index - 1; i++)
- current = current.Next;
- // Если индекс вне пределов списка
- if (current == null || current.Next == null)
- return;
- // Элемент current.Next необходимый к удалению
- // Записываем значение элемента идущего после удаляемого
- ListElement nextAfterCurrent = current.Next.Next;
- // Удаляем элемент
- current.Next = nextAfterCurrent;
- }
- //Задача 4: Оптимизировать добавление эллемента, через хранение ссылки на конец списка
- public void Add(T data)
- {
- var newElement = new ListElement(data);
- ListElement endOfList = null;
- // Если список пуст
- if (_start == null)
- {
- _start = newElement;
- return;
- }
- // Храним текущий элемент
- ListElement current = _start;
- // Пока есть элементы, перебор
- if (endOfList == null)
- {
- while (current.Next != null)
- {
- current = current.Next;
- }
- endOfList = current;
- }
- else current = endOfList;
- // Добавление последнего элемента
- current.Next = newElement;
- endOfList = current;
- }
- public void ForEach(Action<T> body)
- {
- ListElement current = _start;
- while (current != null)
- {
- body(current.Data);
- current = current.Next;
- }
- }
- public class ListElement
- {
- public static T StaticData;
- public T Data;
- public ListElement Next;
- public ListElement(T data)
- {
- Data = data;
- }
- }
- }
- //Задача 5: сделать обобщённую очередь
- class Queue<T>
- {
- private QueueElement _head;
- private QueueElement _tail;
- // Добавление элемента в очередь
- public void Enqueue(T data)
- {
- var newElement = new QueueElement(data);
- if (_head == null)
- {
- _head = newElement;
- _tail = _head;
- }
- else
- {
- _tail.Next = newElement;
- _tail = _tail.Next;
- }
- }
- // Удаление элемента из очереди
- public T Dequeue()
- {
- if (_head == null)
- {
- throw new Exception("Очередь пуста");
- }
- var _result = _head.Data;
- _head = _head.Next;
- return _result;
- }
- // Первый элемент
- public T Peek()
- {
- return _head.Data;
- }
- public class QueueElement
- {
- public T Data;
- public QueueElement Next;
- public QueueElement(T data)
- {
- Data = data;
- }
- }
- }
- class Stack<T>
- {
- private StackElement _head;
- public void Push(T data)
- {
- var newElement = new StackElement(data);
- newElement.Next = _head;
- _head = newElement;
- }
- public T Pop()
- {
- var h = _head;
- _head = h.Next;
- return h.Data;
- }
- public T Peek()
- {
- return _head.Data;
- }
- public Stack<T> Clone()
- {
- Stack<T> newStack = new Stack<T>();
- newStack._head = _head;
- return newStack;
- }
- public class StackElement
- {
- public T Data;
- public StackElement Next;
- public StackElement(T data)
- {
- Data = data;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment