1: public class TwoWayLinkList<T> : IList<T> {
2: private TwoWayNode<T> _head;
3:
4: #region Implementation of IEnumerable
5:
6: public IEnumerator<T> GetEnumerator() {
7: TwoWayNode<T> node = this.Head;
8: while(node != null) {
9: yield return node.Value;
10: node = node.Next;
11: }
12: }
13:
14: IEnumerator IEnumerable.GetEnumerator() {
15: return GetEnumerator();
16: }
17:
18: #endregion
19:
20: #region Implementation of IList<T>
21:
22: /// <summary>
23: /// 列表长度
24: /// </summary>
25: public int Count {
26: get {
27: int count = 0;
28: TwoWayNode<T> node = this._head;
29: while(node != null) {
30: count++;
31: node = node.Next;
32: }
33: return count;
34: }
35: }
36:
37: /// <summary>
38: /// 清空列表
39: /// </summary>
40: public void Clear() {
41: this._head = null;
42: }
43:
44: /// <summary>
45: /// 判断是否为空
46: /// </summary>
47: public bool IsEmpty {
48: get { return this.Head == null; }
49: }
50:
51: public TwoWayNode<T> Head {
52: get { return this._head; }
53: set { this._head = value; }
54: }
55:
56: /// <summary>
57: /// 添加一个数据项至列表尾部
58: /// </summary>
59: /// <param name="value">插入项</param>
60: public void Add(T value) {
61: if(this.Head == null) {
62: this.Head = new TwoWayNode<T>(value);
63: return;
64: }
65: TwoWayNode<T> node = this.Head;
66: while(node.Next != null) {
67: node = node.Next;
68: }
69: node.Next = new TwoWayNode<T>(value, node, null);
70: }
71:
72: /// <summary>
73: /// 在指定位置插入一个数据项
74: /// </summary>
75: /// <param name="value">数据项</param>
76: /// <param name="index">位置</param>
77: public void Insert(T value, int index) {
78: CheckIndex(index);
79: if(index == 0) {
80: this._head = new TwoWayNode<T>(value, null, this._head);
81: return;
82: }
83:
84: TwoWayNode<T> current = this.GetItem(index);
85: current.Previous.Next = current.Next.Previous = new TwoWayNode<T>(value, current.Previous, current.Next);
86: }
87:
88: private void CheckIndex(int index) {
89: if(index < 0 || index >= Count) {
90: throw new ArgumentException("不正确的位置。");
91: }
92: }
93:
94: /// <summary>
95: /// 删除指定位置的数据项
96: /// </summary>
97: /// <param name="index">位置</param>
98: public void Delete(int index) {
99: if(index == 0) {
100: this._head = this._head.Next;
101: return;
102: }
103: TwoWayNode<T> current = this.GetItem(index);
104: current.Previous.Next = current.Next;
105: current.Next.Previous = current.Previous;
106: }
107:
108: /// <summary>
109: /// 获取指定位置的数据项
110: /// </summary>
111: /// <param name="index">位置</param>
112: /// <returns>数据项</returns>
113: public T this[int index] {
114: get {
115: TwoWayNode<T> current = GetItem(index);
116: return current.Value;
117: }
118: set {
119: TwoWayNode<T> current = GetItem(index);
120: current.Value = value;
121: }
122: }
123:
124: private TwoWayNode<T> GetItem(int index) {
125: TwoWayNode<T> current = this.Head;
126: int tempIndex = 0;
127: while(tempIndex < index) {
128: current = current.Next;
129: tempIndex++;
130: }
131: return current;
132: }
133:
134: #endregion
135: }