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(34);
- list.Add(20);
- list.Add(1);
- list.Add(2);
- // Test of Contains() of LinkedList
- Console.WriteLine("Тест метода Contains()");
- var answer = (list.Contains(20)) ? "Содержит" : "Не содержит";
- Console.WriteLine($"Содержит ли лист элемент 20?\nОтвет: {answer}");
- answer = (list.Contains(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");
- string[] titles = new string[]
- {
- "C#4.0",
- "Blood, Sweat and Pixels"
- };
- LibraryEnumerator<Book> library = new LibraryEnumerator<Book>();
- for (int i = 0; i < titles.Length; i++)
- {
- library.AddHead(new Book(titles[i]));
- }
- foreach (Book item in library)
- {
- 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
- {
- public string Name;
- public Book(string name)
- {
- Name = name;
- }
- }
- class LibraryEnumerator<T> : IEnumerable<T>
- {
- private LibraryNode _head;
- public LibraryEnumerator()
- {
- _head = null;
- }
- public void AddHead(T t)
- {
- LibraryNode node = new LibraryNode(t);
- node.Next = _head;
- _head = node;
- }
- public IEnumerator<T> GetEnumerator()
- {
- LibraryNode current = _head;
- while (current != null)
- {
- yield return current.Data;
- current = current.next;
- }
- }
- IEnumerator IEnumerable.GetEnumerator()
- {
- return GetEnumerator();
- }
- public class LibraryNode
- {
- public LibraryNode next;
- private T _data;
- public LibraryNode(T t)
- {
- next = null;
- _data = t;
- }
- public LibraryNode Next
- {
- get { return next; }
- set { next = value; }
- }
- public T Data{
- get { return _data; }
- set { _data = value; }
- }
- }
- }
- //Задача 2: Сделать метод Contains. Проверяет есть ли заданное значенеи в спике
- //Задача 3: Сделать метод Remove, который удаляет эллемент под каким-либо номером
- //Задача 4: Оптимизировать добавление эллемента, через хранение ссылки на конец списка
- class LinkedList<T>
- {
- public ListElement _start;
- public ListElement _end = null;
- public LinkedList()
- {
- _start = null;
- }
- public int Count
- {
- get
- {
- int count = 0;
- ForEach((x) => count++);
- return count;
- }
- }
- // Задача 2. Итеративный метод поиска элемента
- public bool Contains(T element)
- {
- ListElement current = _start;
- while (current != null)
- {
- if (current.Data.Equals(element))
- return true;
- current = current.Next;
- }
- return false;
- }
- // Задача 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);
- if (_end == null)
- {
- _end = _start = newElement;
- _start.Next = _end;
- }
- else
- {
- _end.Next = newElement;
- _end = newElement;
- }
- }
- 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