-
Notifications
You must be signed in to change notification settings - Fork 0
/
CustomeLList.cs
119 lines (106 loc) · 2.31 KB
/
CustomeLList.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
using System.Collections;
namespace LList;
public class CustomeLList<T> : IEnumerable<T>
{
public Node<T> Head { get; set; }
public int Count { get; set; }
public CustomeLList()
{
Head = null;
Count = 0;
}
public void AddNode(T data)
{
var node = new Node<T>(data);
if(Head is null)
{
Head = node;
}
else
{
var current = Head;
while (current.Next != null)
{
current = current.Next;
}
current.Next = node; //new head
}
Count++;
}
public void Insert(T data, int index)
{
var node = new Node<T>(data);
var current = Head;
if(index == 0)
{
node.Next = Head;
Head = node;
return;
}
if(index < 0 || index > Count)
{
throw new IndexOutOfRangeException($"index out of range");
}
while (--index > 0)
{
current = current.Next;
}
node.Next = current.Next;
current.Next = node;
return;
}
public T Remove(T data)
{
if (Head == null)
return data;
if (Head.Data.Equals(data))
{
Head = Head.Next;
return data;
}
var current = Head;
while (current.Next != null)
{
if (current.Next.Data.Equals(data))
{
current.Next = current.Next.Next;
return data;
}
current = current.Next;
}
return data;
}
public T this[int i]
{
get
{
if(i > Count)
{
throw new IndexOutOfRangeException($"index out of range");
}
var current = Head;
while (i-- != 0)
{
current = current.Next;
}
return current.Data;
}
}
public IEnumerator<T> Enumerator()
{
var current = Head;
while (current != null)
{
yield return current.Data;
current = current.Next;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return Enumerator();
}
public IEnumerator<T> GetEnumerator()
{
return Enumerator();
}
}