-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedArray.cs
More file actions
106 lines (97 loc) · 2.41 KB
/
LinkedArray.cs
File metadata and controls
106 lines (97 loc) · 2.41 KB
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace D_A
{
internal class LinkedArray<T>
{
Node<T>? start;
Node<T>? current;
public int Count { get; set; }
public void Add(T val)
{
Node<T> node = new(val);
if (start == null)
{
start = node;
}
else
{
if (current == null)
{
start.next = node;
current = node;
}
else
{
current.next = node;
current = node;
}
}
++Count;
}
public T Get(int idx)
{
if (start == null || (current == null && idx > 0) || (current?.next == null && Count == idx))
throw new IndexOutOfRangeException();
var n = start;
for (int i = 0; i < idx; i++)
{
n = n?.next;
}
return n.data;
}
public void Set(int idx, T val)
{
if (start == null || (current == null && idx > 0) || (current?.next == null && Count == idx) || idx > Count)
{
Add(val);
return;
}
var n = start;
for (int i = 0; i < idx; i++)
{
n = n?.next;
}
var tmp = new Node<T>(val)
{
next = n.next
};
n.next = tmp;
++Count;
}
public T First()
{
if (start == null)
throw new IndexOutOfRangeException();
return start.data;
}
public T Last()
{
if (current == null)
throw new IndexOutOfRangeException();
return current.data;
}
public T this[int idx]
{
get { return Get(idx); }
set { Set(idx, value); }
}
}
class Node<T>
{
public T data;
public Node<T>? next;
public Node(T data, Node<T> next)
{
this.data = data;
this.next = next;
}
public Node(T data)
{
this.data = data;
}
}
}