public StaticSeqList { private int[] list; private int count; }
可以定义一些方便使用的属性和方法
1 2 3 4 5 6 7 8 9
public int Count { get { return count; } } public bool IsEmpty { get { return count <= 0; } } public bool IsFull { get { return count >= list.Length; } }
public StaticSeqList(int capacity) { count = 0; list = new int[capacity]; }
实现的操作
顺序表的操作主要就是增、删、改、查。
添加
添加分为:
添加到末尾
插入到某个位置
添加到末尾
1 2 3 4 5 6 7 8
public void Add(int elem) { if (IsFull) { throw new OutOfMemoryException(); } list[count++] = elem; }
插入到某个位置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
public void Insert(int index, int elem) { if (index < 0 || index > count) { //可在末尾插入 throw new IndexOutOfRangeException(); } if (IsFull) { throw new OutOfMemoryException(); } for (int i = count - 1; i >= index; i--) { list[i + 1] = list[i]; } list[index] = elem; count++; }
移除
移除分为:
根据索引号移除
根据元素移除
根据索引号移除
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
public int RemoveAt(int index) { if (IsOutOfRange(index)) { throw new IndexOutOfRangeException(); } if (IsEmpty) { throw new Exception("List is empty."); } int elem = list[index]; for (int i = index; i < count - 1; i++) { list[i] = list[i + 1]; } count--; return elem; }
private void CutDownList() { int newLength = list.Length - segmentLength; int[] tmp = list; list = new int[newLength]; for (int i = 0; i < count; i++) { list[i] = tmp[i]; } }
public int RemoveAt(int index) { if (IsOutOfRange(index)) { throw new IndexOutOfRangeException(); } if (IsEmpty) { throw new Exception("List is empty."); }
int elem = list[index]; for (int i = index; i < count - 1; i++) { list[i] = list[i + 1]; } count--;