**
c# 实现线性表(一)(顺序表(MyList))
**
你好! 本篇文章将用C#向你讲述一个完整的顺序表
发稿理由
网上有很多关于c/c++关于线性表的内容,但C#的却很少,因为C#有自己的list,里面已经封装好了,下面我将用我自己写的代码创建一个自己的Mylist
1.参考文章:https://blog.csdn.net/qq_40985921/article/details/90709669
2.参考文章:https://www.bilibili.com/video/BV1px411f7pe?p=33
首先定义线性表的接口,方便以后的单链表等
还可添加其他的功能
接下来创建Mylist的泛型类并继承接口IList
创建泛型数组array
创建count来记录当前的元素个数
分别创建有参和无参两个构造函数
用构造函数来初始化数组的长度
继续创建两个属性,方便调用
完成了这些就可开始方法的书写了
Add添加元素
Insert插入元素
获取元素
为了方便使用索引器来获取元素
RemoveAt移除元素
Remove移除元素
最后完整代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApp3
{
class MyList<T>:Ilsit<T>
{
private T[] array;//创建一个泛型的数组来存储数据
private int count = 0;//表示当前添加的元素个数
//创建最大容量的属性
public int capaity
{
//最大容量等于数组的长度
get { return array.Length; }
}
public int Count
{
get { return this.count; }
}
public MyList(int maxSize)
{
if (maxSize > 0)
{
array = new T[maxSize];
}
}
public MyList()
{
//当不传入参数时,默认长度为0
array = new T[0];
}
public void Add(T item)
{
//当最大的容量为0时,给定默认长度
if (capaity == 0)
{
array = new T[2];
}
//当前数组中的元素个数大于等于最大容量时,扩充
else if (count >= capaity)
{
var newArray = new T[count * 2];
//for循环的代码可使用Array类中的copy方法Array.Copy(array, newArray, count);
for (int i = 0; i < array.Length; i++)
{
newArray[i] = array[i];
}
array = newArray;
}
array[count] = item;
count++;
}
public void Insert(T item, int index)
{
if (capaity == 0)
{
throw new Exception("list为空");
}
if (index < 0||index>capaity)
{
throw new Exception("index不在范围内");
}
//当最大的容量为0时,给定默认长度
if (capaity == 0)
{
array = new T[2];
}
//当前数组中的元素个数大于等于最大容量时,扩充
else if (count >= capaity)
{
var newArray = new T[count * 2];
//for循环的代码可使用Array类中的copy方法Array.Copy(array, newArray, count);
for (int i = 0; i < array.Length; i++)
{
newArray[i] = array[i];
}
array = newArray;
}
//整体向后移动index和index后元素
for (int i =count-1 ; i >=index; i--)
{
array[i + 1] = array[i];
}
array[index] = item;
count++;
}
public T GetItem(int index)
{
if (capaity == 0)
{
throw new Exception("list为空");
}
if (index < 0 || index >= count)
{
throw new Exception("index超出范围");
}
return array[index];
}
public T this[int index]
{
get { return GetItem(index); }
}
public void RemoveAt(int index)
{
if (capaity == 0)
{
throw new Exception("list为空");
}
if (index < 0 || index > capaity)
{
throw new Exception("index不在范围内");
}
for (int i = index; i < count-1; i++)
{
array[i] = array[i + 1];
}
count--;
}
public void Remove(T item)
{
if (capaity == 0)
{
throw new Exception("list为空");
}
for (int i = 0; i < count; i++)
{
if (item.Equals(array[i]))
{
for (int j = i; j < count-1; j++)
{
array[i] = array[i + 1];
}
count--;
break;
}
}
}
}
}