Advertisement
Guest User

Untitled

a guest
Jun 21st, 2018
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.23 KB | None | 0 0
  1. public class DoublyNode<T>// описание элемента
  2. {
  3. public DoublyNode(T data)
  4. {
  5. Data = data;
  6. }
  7. public T Data { get; set; }
  8. public DoublyNode<T> Previous { get; set; }
  9. public DoublyNode<T> Next { get; set; }
  10. }
  11. public class DoublyLinkedList<T> // двусвязный список
  12. {
  13. DoublyNode<T> head; // головной/первый элемент
  14. DoublyNode<T> tail; // последний/хвостовой элемент
  15. int count; // количество элементов в списке
  16.  
  17. // добавление элемента
  18. public void Add(T data)
  19. {
  20. DoublyNode<T> node = new DoublyNode<T>(data);
  21.  
  22. if (head == null)
  23. head = node;
  24. else
  25. {
  26. tail.Next = node;
  27. node.Previous = tail;
  28. }
  29. tail = node;
  30. count++;
  31. }
  32. public void AddFirst(T data)
  33. {
  34. DoublyNode<T> node = new DoublyNode<T>(data);
  35. DoublyNode<T> temp = head;
  36. node.Next = temp;
  37. head = node;
  38. if (count == 0)
  39. tail = head;
  40. else
  41. temp.Previous = node;
  42. count++;
  43. }
  44. // удаление
  45. public bool Remove(T data)
  46. {
  47. DoublyNode<T> current = head;
  48.  
  49. // поиск удаляемого узла
  50. while (current != null)
  51. {
  52. if (current.Data.Equals(data))
  53. {
  54. break;
  55. }
  56. current = current.Next;
  57. }
  58. if(current!=null)
  59. {
  60. // если узел не последний
  61. if(current.Next!=null)
  62. {
  63. current.Next.Previous = current.Previous;
  64. }
  65. else
  66. {
  67. // если последний, переустанавливаем tail
  68. tail = current.Previous;
  69. }
  70.  
  71. // если узел не первый
  72. if(current.Previous!=null)
  73. {
  74. current.Previous.Next = current.Next;
  75. }
  76. else
  77. {
  78. // если первый, переустанавливаем head
  79. head = current.Next;
  80. }
  81. count--;
  82. return true;
  83. }
  84. return false;
  85. }
  86.  
  87. public int Count { get { return count; } }
  88. public bool IsEmpty { get { return count == 0; } }
  89.  
  90. public void Clear()
  91. {
  92. head = null;
  93. tail = null;
  94. count = 0;
  95. }
  96.  
  97. public bool Contains(T data)
  98. {
  99. DoublyNode<T> current = head;
  100. while (current != null)
  101. {
  102. if (current.Data.Equals(data))
  103. return true;
  104. current = current.Next;
  105. }
  106. return false;
  107. }
  108.  
  109.  
  110.  
  111.  
  112.  
  113.  
  114. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement