Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Linq;
- namespace tren
- {
- public class Program
- {
- public static void Main(string[] args)
- {
- //односвчзный список
- LinkedList<string> linkedlist = new LinkedList<string>();
- linkedlist.Add("tom");
- linkedlist.Add("sam");
- linkedlist.Add("max");
- foreach(string item in linkedlist)
- {
- Console.WriteLine(item);
- }
- linkedlist.Remove("tom");
- foreach (string item in linkedlist)
- {
- Console.WriteLine(item);
- }
- linkedlist.AddFirst("kirill");
- foreach (string item in linkedlist)
- {
- Console.WriteLine(item);
- }
- }
- public class Node<T>//создание узлов
- {
- public Node(T data)
- {
- Data = data;
- }
- public T Data { get; set; }
- public Node<T> Next { get; set; }
- }
- public class LinkedList<T> : IEnumerable<T>
- {
- Node<T> head;
- Node<T> tail;
- int count;
- public void Add(T data)//добавление
- {
- Node<T> node = new Node<T>(data);
- if (head == null)//проверка пуст ли список
- {
- head = node;//устанавливаем начало
- }
- else
- {
- tail.Next = node;//ссылка на созданный элемент
- }
- tail = node;
- count++;
- }
- public void AddFirst(T data)//добавление в начало
- {
- Node<T> node = new Node<T>(data);//создание нового нода
- node.Next = head;//ссылка на существующий хэд
- head = node;//переопределение хэда на только чтро созданный
- if(count == 0)
- {
- tail = head;//если нет больше нодов чтобы ссылки хэд тейл были на единтсвенном
- }
- count++;
- }
- IEnumerator IEnumerable.GetEnumerator()//реализация интерфейса
- {
- return ((IEnumerable)this).GetEnumerator();
- }
- IEnumerator<T> IEnumerable<T>.GetEnumerator()
- {
- Node<T> current = head;
- while(current != null)
- {
- yield return current.Data;
- current = current.Next;
- }
- }
- public bool Remove(T data)//удаление объекта
- {
- Node<T> current = head;
- Node<T> previous = null;
- while (current != null)
- {
- if(current.Data.Equals(data))//проверка на ввод данных
- {
- if (previous != null)//если узел в середине или в конце
- {
- previous.Next = current.Next;//приравнивает ссылка ссылку проскакивая элемент
- if (current.Next == null)//если каррент последний
- {
- tail = previous;
- }
- }
- else
- {
- head = head.Next;//если узел в начале
- if(head == null)
- {
- tail = null;
- }
- }
- count--;
- return true;
- }
- previous = current;
- current = current.Next;
- }
- return false;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement