-
Notifications
You must be signed in to change notification settings - Fork 0
/
SinglyLinkedList.cs
111 lines (94 loc) · 2 KB
/
SinglyLinkedList.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
namespace LinkedList;
public class SinglyLinkedList<T>
{
private class Node
{
public T Data;
public Node Next;
public Node(T data)
{
this.Data = data;
this.Next = null;
}
}
private Node head;
private Node tail;
private int length;
public int Length
{
get { return this.length; }
private set { length = value; }
}
public SinglyLinkedList()
{
head = null;
tail = null;
length = 0;
}
public bool IsEmpty()
{
return length == 0;
}
public void Add(T data)
{
var node = new Node(data);
if (IsEmpty())
{
head = tail = node;
}
else
{
tail.Next = node;
tail = node;
}
length++;
}
public T Get(int index)
{
if (IsEmpty() || index < 0 || index >= length)
{
throw new IndexOutOfRangeException("Index out of range.");
}
var current = head;
for (int i = 0; i < index; i++)
{
current = current.Next;
}
return current.Data;
}
public void Delete(int index)
{
if (IsEmpty() || index < 0 || index >= length)
{
throw new IndexOutOfRangeException("Index out of range.");
}
if (index == 0)
{
head = head.Next;
if (length == 1)
{
tail = null;
}
}
else
{
var current = head;
for (int i = 0; i < index - 1; i++)
{
current = current.Next;
}
current.Next = current.Next.Next;
if (index == length - 1) // If the last element is being deleted
{
tail = current;
}
}
length--;
}
public void Clear()
{
head = null;
tail = null;
length = 0;
}
}