基础实现部分
1. 添加结点元素(实现IList.Insert、IList.Add)
1
public void Insert(int index, object value)
2
{
3
// 首先验证结点值的有效性。
4
this.Validate(index, value);
5
6
7
if (index == 0)
8
{
9
// 插入首结点前
10
this._head = new ListNode(value, this._head);
11
}
12
else
13
{
14
ListNode lastNode = this.FindByIndex(index - 1);
15
16
lastNode.NextNode = new ListNode(value, this.FindByIndex(index));
17
}
18
19
this._nodeCount += 1;
20
21
//this._version += 1;
22
}
23
24
public int Add(object value)
25
{
26
// 首先验证结点值的有效性。
27
this.Validate(value);
28
29
this._tail.NextNode = new ListNode(value);
30
this._tail = this._tail.NextNode;
31
32
this._nodeCount += 1;
33
34
return this._nodeCount - 1;
35
36
//this._version += 1;
37
}
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
2. 删除结点元素(自定义一个RemoveNode、实现IList.RemoveAt、IList.Remove)
1
protected virtual void RemoveNode(int index, ListNode node)
2
{
3
if (index == 0)
4
{
5
// 如果是首结点
6
this._head = node.NextNode;
7
}
8
else
9
{
10
ListNode lastNode = this.FindByIndex(index - 1);
11
12
lastNode.NextNode = node.NextNode;
13
14
if (node == this._tail)
15
{
16
// 如果是尾结点
17
this._tail = lastNode;
18
}
19
}
20
21
this._nodeCount -= 1;
22
23
//this._version += 1;
24
}
25
26
public void RemoveAt(int index)
27
{
28
// 首先验证结点值的有效性。
29
this.Validate(index);
30
31
this.RemoveNode(index, this.FindByIndex(index));
32
}
33
34
public void Remove(object value)
35
{
36
// 首先验证结点值的有效性。
37
this.Validate(value);
38
39
this.RemoveAt(this.FindByValue(value));
40
}
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
3. 按索引获取结点以及根据结点值返回结点索引(实现IList索引器、IList.IndexOf)
1
public object this[int index]
2
{
3
get
4
{
5
// 首先验证结点值的有效性。
6
this.Validate(index);
7
8
return this.FindByIndex(index).Data;
9
}
10
set
11
{
12
this.Insert(index, value);
13
}
14
}
15
16
public int IndexOf(object value)
17
{
18
// 首先验证结点值的有效性。
19
this.Validate(value);
20
// 根据结点值查找结点。
21
return this.FindByValue(value);
22
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
4. 其他IList成员的实现
1
public bool Contains(object value)
2
{
3
// 首先验证结点值的有效性。
4
if (this.IndexOf(value) > -1)
5
{
6
return true;
7
}
8
else
9
{
10
return false;
11
}
12
}
13
14
public void Clear()
15
{
16
this._head.NextNode = null;
17
18
this._tail = _head;
19
20
this._nodeCount = 0;
21
22
//this._version = 0;
23
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
查看下一部分
浙公网安备 33010602011771号