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)
- {
- //двухсвязный список
- DoubleLinkedlist<string> linkedlist = new DoubleLinkedlist<string>();
- linkedlist.Add("tom");
- linkedlist.Add("sam");
- linkedlist.Add("kirill");
- foreach(string s in linkedlist)
- {
- Console.WriteLine(s);
- }
- foreach(string s in linkedlist)
- {
- Console.WriteLine(s);
- }
- linkedlist.Remove("tom");
- linkedlist.AddFirst("max");
- foreach(string s in linkedlist)
- {
- Console.WriteLine(s);
- }
- Console.WriteLine(linkedlist.Contains("max"));
- }
- public class DoublyNode<T>//Создание узлов
- {
- public DoublyNode(T data)
- {
- Data = data;
- }
- public T Data { get; set; }
- public DoublyNode<T> Previous { get; set; }
- public DoublyNode<T> Next { get; set; }
- }
- public class DoubleLinkedlist<T>: IEnumerable<T>//двухсвязный список
- {
- DoublyNode<T> head;//головной(первый) элемент
- DoublyNode<T> tail;//хвостовой(последний) элемент
- int count;//счетчик
- public void Add(T data)
- {
- DoublyNode<T> node = new DoublyNode<T>(data);
- if(head == null)
- {
- head = node;
- }
- else
- {
- tail.Next = node;
- node.Previous = tail;
- }
- tail = node;
- count++;
- }
- public void AddFirst(T data)
- {
- DoublyNode<T> node = new DoublyNode<T>(data);
- if(head == null)
- {
- head = node;
- tail = node;
- }
- else
- {
- head.Previous = node;
- node.Next = head;
- }
- head = node;
- count++;
- }
- public bool Remove(T data)//удаление
- {
- DoublyNode<T> current = head;
- while(current != null)//поиск удаляемого узла
- {
- if(current.Data.Equals(data))
- {
- break;
- }
- current = current.Next;
- }
- if(current != null)
- {
- if(current.Next != null)//если узел не последний
- {
- current.Next.Previous = current.Previous;//ссылка след элемента приравнивается с предыдущему элементу
- }
- else
- {
- tail = current.Previous;//если последний, переустанавливаем tail
- }
- if (current.Previous != null)//если узел не первый
- {
- current.Previous.Next = current.Next;//ссылка пред элемента приравнивается к следующему элементу
- }
- else
- {
- head = current.Next;//если первый, переустанавливаем head
- }
- count--;
- return true;
- }
- return false;
- }
- public bool Contains(T data)//содержит ли искомое
- {
- DoublyNode<T> current = head;
- while(current != null)
- {
- if(current.Data.Equals(data))
- {
- return true;
- }
- current=current.Next;
- }
- return false;
- }
- IEnumerator IEnumerable.GetEnumerator()
- {
- return ((IEnumerable)this).GetEnumerator();
- }
- IEnumerator<T> IEnumerable<T>.GetEnumerator()
- {
- DoublyNode<T> current = head;
- while (current != null)
- {
- yield return current.Data;
- current = current.Next;
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement