-
Notifications
You must be signed in to change notification settings - Fork 0
/
DoublyLinkedList.cs
103 lines (87 loc) · 1.95 KB
/
DoublyLinkedList.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
using System.Collections;
namespace CustomHashTable;
public class DoublyLinkedList<TData> : IEnumerable<TData>
{
private DoublyLinkedListNode<TData>? _head;
private int _count;
public int Count => _count;
public DoublyLinkedList()
{
_head = null;
}
public void Add(TData data)
{
var newNode = new DoublyLinkedListNode<TData>(data);
if (_head == null)
{
_head = newNode;
}
else
{
_head.Previous = newNode;
newNode.Next = _head;
_head = newNode;
}
_count++;
}
public void Remove(TData data)
{
var node = Find(data);
if (node != null)
{
if (node.Next != null)
{
node.Data = node.Next.Data;
node.Next = node.Next.Next;
}
else if (node.Previous != null)
{
node.Data = node.Previous.Data;
node.Previous = node.Previous.Next;
}
else
{
_head = null;
}
}
_count++;
}
public DoublyLinkedListNode<TData>? Find(TData data)
{
var node = _head;
if (_head == null)
{
return null;
}
while (node != null)
{
if (data.Equals(node.Data))
{
return node;
}
node = node.Next;
}
return null;
}
public bool Contains(TData data)
{
return Find(data) != null;
}
public IEnumerator<TData> GetEnumerator()
{
var node = _head;
if (_head == null)
{
yield break;
}
while (node != null && node.Data != null)
{
yield return node.Data;
node = node.Next;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}