数据结构 Via C# (2) 顺序存储结构的线性表
2021-06-08 05:04
标签:存储 ret row equal 组合 顺序存储 存在 exce show
上文讲了一些数据结构的基本概念,现在开始进入正题,今天学习最简单的线性表,线性表分为顺序存储结构和链式存储结构,本文讲顺序存储结构的线性表。
在C#的面向对象的世界中,我们一般都会对一个东西进行抽象,线性表的接口如下(只定义了一些最基本的操作,一些复杂的操作都是基于这些基本的操作组合实现的):
////// c#线性表接口 /// public interface ICsharpList { /// /// 指示线性表是否为空 /// /// bool IsListEmpty(); /// /// 清空线性表 /// void ClearList(); /// /// 将第i个位置的元素返回 /// /// /// T GetItem(int i); /// /// 定位元素item在线性表中的位置,若不存在则返回-1 /// /// /// int LocateItem(T item); /// /// 在第i个位置插入元素item /// /// /// void ListInsert(int i, T item); /// /// 删除线性表第i个位置的元素,并返回该删除的元素 /// /// /// T ListDelete(int i); /// /// 获取线性表的长度 /// /// int ListLength(); }
顺序存储结构的线性表实现如下:
////// 顺序存储结构线性表 /// public class CsharpSqList : ICsharpList { /// /// 最大长度 /// private readonly int _maxLength; /// /// 通过数组来实现顺序线性表 /// public T[] Arrary { get; set; } /// /// 指示线性表的长度 /// public int Length { get; set; } /// /// 构造函数 /// /// public CsharpSqList(int maxLength) { _maxLength = maxLength; Arrary = new T[_maxLength]; } /// /// 索引器 /// /// /// public T this[int index] { get { if (index >= 0 && index 1) return Arrary[index]; return default(T); } set { if (index >= 0 && index 1) Arrary[index] = value; } }
////// 清空线性表 /// /// ///
public void ClearList()
{
if (Length == 0)
return;
for (var i = 0; i {
Arrary[i] = default(T);
}
Length = 0;
} ////// 获取第i个元素 /// /// /// public T GetItem(int i) { if (IsListEmpty()) throw new Exception("空线性表"); if(i0||i>Length-1) throw new Exception("非法参数"); return Arrary[i]; } /// /// 是否为空线性表 /// /// public bool IsListEmpty() { return Length == 0; } /// /// 删除第i个元素 /// /// /// public T ListDelete(int i) { if (IsListEmpty()) throw new Exception("空线性表"); if (i 0 || i > Length - 1) throw new Exception("非法参数"); var item = this[i];//保存被删除的元素 if (i 1) //如果删除的元素不是最后一个则将后继的元素往前移动一步 { for (var j = i; j ) { Arrary[j] = Arrary[j + 1]; } } Length--;//将长度减一 return item; } /// /// 插入一个元素到第i个位置 /// /// /// public void ListInsert(int i, T item) { if(Length==_maxLength) throw new Exception("线性表已满"); if(i0||i>Length) throw new Exception("非法参数"); if (i 1) //如果插入的元素不是最后一个则将后继的元素往后移动一步 { for (var j = Length-1; j > i; j--) { Arrary[j + 1] = Arrary[j]; } } Arrary[i] = item; Length++;//长度加一 } /// /// 获取长度 /// /// public int ListLength() { return Length; } /// /// 定位某个元素的第一个位置,若不存在则返回-1 /// /// /// public int LocateItem(T item) { for (var i = 0; i ) { if (Arrary[i].Equals(item)) return i; } return -1; } }
代码比较简单,就不一一解释了。
数据结构 Via C# (2) 顺序存储结构的线性表
标签:存储 ret row equal 组合 顺序存储 存在 exce show
原文地址:https://www.cnblogs.com/aprilwarm/p/dataStructureViaCsharp2.html
文章标题:数据结构 Via C# (2) 顺序存储结构的线性表
文章链接:http://soscw.com/index.php/essay/92070.html