C#顺序表-C#数据结构--顺序表(基础入门)
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ListDS { public interface IDS<T> { int Count { get; } //求长度 void Clear(); //清空操作 bool IsEmpty { get; } //判断线性表是否为空 } //定义线性表 public interface IListDS<T> : IDS<T> { void Append(T item); //附加操作 void Insert(T item, int index); //插入操作 T Delete(int index); //删除操作 T GetElem(int index); //取表元 int Locate(T value); //按值查找 } //定义顺序表 public class SeqList<T> : IListDS<T> { private int maxsize; //顺序表的容量 private T[] data; //数组,用于存储顺序表中的数据元素 private int last; //指示顺序表最后一个元素的位置 //索引器 public T this[int index] { get { return data[index]; } set { data[index] = value; } } //最后一个数据元素位置属性 public int Last { get { return last; } } //容量属性 public int Maxsize { get { return maxsize; } set { maxsize = value; } } //构造器 public SeqList(int size) { data = new T[size]; maxsize = size; last = -1; } //求顺序表的长度 public int GetLength() { return last + 1; } //清空顺序表 public void Clear() { last = -1; } //判断顺序表是否为空 public bool IsEmpty() { if (last == -1) { return true; } else { return false; } } public bool IsFull() { if (last == maxsize - 1) { return true; } else { return false; } } public void Append(T item) { if (IsFull()) { Console.WriteLine("List is full"); return; } data[++last] = item; } public void Insert(T item, int i) { if (IsFull()) { Console.WriteLine("List is full"); return; } if (i < 1 || i > last + 2) { Console.WriteLine("Position is error!"); return; } if (i == last + 2) { data[last + 1] = item; } else { for (int j = last; j >= i - 1; --j) { data[j + 1] = data[j]; } data[i - 1] = item; } ++last; } public T Delete(int index) { T tmp = default(T); if (IsEmpty()) { Console.WriteLine("List is empty"); return tmp; } if (index < 1 || index > last + 1) { Console.WriteLine("Position is error!"); return tmp; } if (index == last + 1) { tmp = data[last--]; } else { tmp = data[index - 1]; for (int j = index; j <= last; ++j) { data[j] = data[j + 1]; } } --last; return tmp; } public T GetElem(int index) { if (IsEmpty() || (index < 1) || (index > last + 1)) { Console.WriteLine("List is empty or Position is error!"); return default(T); } return data[index - 1]; } public int Locate(T value) { if (IsEmpty()) { Console.WriteLine("List is Empty!"); return -1; } int i = 0; for (i = 0; i <= last; ++i) { if (value.Equals(data[i])) { break; } } if (i > last) { return -1; } return i; } public int Count { get { return last; } } bool IDS<T>.IsEmpty { get { if (last == - 1) { return true; } else { return false; } } } } class Program { static void Main(string[] args) { SeqList <int> list=new SeqList<int> (10); for (int i = 0; i < 8; i++) { list.Append(i+1);//附加 Console.Write("{0} ", list[i]);//输出 } } } }