線性表的實現方式
?順序表
線性表的順序存儲是指在內存中用一塊地址連續的空間依次存放線性表的數據元素,用這種方式存儲的線性表叫順序表。
特點:表中相鄰的數據元素在內存中存儲位置也相鄰。
順序表接口實現:
方法名 | 參數 | 返回值 | 描述 |
---|---|---|---|
GetLength | 無 | int | 返回線性表的當前元素個數(長度)。 |
Clear | 無 | void | 清空線性表,重置內部元素計數為0,釋放存儲空間。 |
IsEmpty | 無 | bool | 判斷線性表是否為空(元素個數為0),返回true ;否則返回false 。 |
Add | T item | void | 在表尾追加元素。若容量不足,自動擴容。 |
Insert |
? | void | 在指定索引處插入元素。索引需滿足?0 ≤ index ≤ count ,否則拋出異常。 |
Delete | int index | T | 刪除并返回指定索引的元素。索引需滿足?0 ≤ index < count ,否則拋出異常。 |
GetEle | int index | T | 獲取指定索引的元素。索引越界時拋出異常。 |
索引器 | int index | T | 通過索引訪問元素(如?list[0] )。索引越界時拋出異常。 |
Locate | T value | int | 返回第一個與value 相等的元素索引,未找到返回-1 。 |
代碼: IList.cs
internal interface IList<T>
{int GetLength();//求長度void Clear(); //清空bool IsEmpty(); //判斷是否為空void Add(T item);// 添加void Insert(T item ,int index);//插入T Delete(int index);//刪除T GetEle(int index);//取表元T this[int index] { get; }//定義一個索引器, 獲取元素int Locate(T value); //按值查找
}
順序表的實現
代碼的實現:SeqList.cs
1、定義字段:
private T[] data; //用來存儲數據private int count ;//表示存了多少個數據
2、實現構造函數 :
(1)? 實現構造函數
public SeqList(int size) //size:數組的最大容量{data = new T[size]; // 初始化數組count = 0; // 元素個數初始為0}
(2)??默認構造函數(委托調用)
public SeqList():this(10) //默認構造函數 容量是10
{}
3、添加基礎方法
(1)??獲取當前元素數量
public int GetLength()
{return count;
}
(2)? 判斷是否為空?
public bool IsEmpty()
{return count == 0;
}
(3)? 清空列表?
public void Clear()
{count = 0;
}
4. 實現核心操作
(1) 添加元素(到末尾)
public void Add(T item)
{if(count == data.Length) //當前數組已經存滿{Console.WriteLine("前順序表已經存滿,不允許再存入");}else{data[count] = item;count++;}
}
?(2)? 插入元素(到指定位置)
public T GetEle(int index)
{if(index>=0&& index<=count-1){return data[index];}else{Console.WriteLine("索引不存在");return default(T);}
}
(3) 刪除元素(按索引)
public T Delete(int index)
{T temp = data[index];for (int i = index + 1; i < count; i++){data[i - 1] = data[i];}count--;return temp;
}
5. 實現訪問與查找
(1) 按索引獲取元素
public T GetEle(int index)
{if(index>=0&& index<=count-1){return data[index];}else{Console.WriteLine("索引不存在");return default(T);}
}
(2) 索引器
public T this[int index]
{get { return GetEle(index); }
}
(3) 按值查找索引
public int Locate(T value)
{for (int i = 0; i < count; i++){if (data[i].Equals(value)){return i;}}return -1;
}
代碼使用:Program.cs
namespace _001_List
{internal class Program{static void Main(string[] args){SeqList<string> seqList = new SeqList<string>();seqList.Add("123");seqList.Add("145");seqList.Add("167");Console.WriteLine("GetEle:"+seqList.GetEle(0));Console.WriteLine("this:"+seqList[0]);seqList.Insert("777", 1);for (int i = 0;i<seqList.GetLength(); i++){Console.Write(seqList[i]+ " ");}Console.WriteLine("seqList:");seqList.Delete(0);for (int i = 0; i < seqList.GetLength(); i++){Console.Write(seqList[i] + " ");}Console.WriteLine("seqList:");seqList.Clear();Console.WriteLine(seqList.GetLength()); Console.ReadKey();}}
}
輸出結果: