/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
public interface ILinearList<T>
{
int Length { get; }
bool IsEmpty();
void Clear();
T GetItem(int index);
int LocateItem(T t);
void Insert(T item, int index);
void Add(T item);
void Delete(int index);
}
/// <summary>
/// 顺序线性表
/// </summary>
/// <typeparam name="T"></typeparam>
public class SequentialList<T> : ILinearList<T>
{
private T[] list;
private int count = 0;
public SequentialList(int maxSize)
{
list = new T[maxSize];
}
public int Length => count;
public void Add(T item)
{
if (count == list.Length)
{
throw new Exception("表存储已经满了");
}
count++;
list[count - 1] = item;
}
public void Clear()
{
count = 0;
}
public void Delete(int index)
{
if (index < 0 || index > count - 1)
{
throw new Exception("索引不正确");
}
count--;
for (int i = index; i < count; i++)
{
list[i] = list[i + 1];
}
}
public T GetItem(int index)
{
return list[index];
}
public void Insert(T item, int index)
{
if (count == list.Length)
{
throw new Exception("表存储已经满了");
}
if (index < 0 || index > count - 1)
{
throw new Exception("索引不正确");
}
count++;
for (int i = count + 1; i < index; i--)
{
list[i] = list[i - 1];
}
list[index] = item;
}
public bool IsEmpty()
{
return count == 0;
}
public int LocateItem(T t)
{
for (int i = 0; i < count; i++)
{
if (list[i].Equals(t))
{
return i;
}
}
return -1;
}
}
顺序线性表
最新推荐文章于 2024-10-02 10:19:33 发布
本文介绍了线性列表的接口定义及其顺序线性表的实现。顺序线性表支持增删查改操作,包括获取长度、判断是否为空、清除元素、获取指定位置元素、插入元素、删除元素以及查找元素的功能。通过`SequentialList<T>`类实现了接口`ILinearList<T>`,并提供了异常处理来确保操作的正确性。
摘要由CSDN通过智能技术生成