標籤:style blog http io ar sp for strong 資料
1、線性表
概念::零個或多個資料元素的有序序列。
描述:
2、線性表的抽象資料類型:
ADT線性表
Data:線性表的資料對象集合為{a1,a2,...,an},每個元素的類型均為DataType。其中除第一個元素a1外,每一個元素有且只有一個直接前驅元素,除了最後一個元素an外,每一個元素有且只有一個直接後繼元素,資料元素之間的關係是一對一的關係。
Operation
Init(*L):初始化操作,建立一個空的線性表;
IsEmpty(*L):判斷線性表是否為空白,若為空白,則返回true,否則返回false;
Clear(*L):清空線性表;
GetElem(*L,i):返回線性表位置為i的元素;
LocateElem(*L,e):返回線性表中與元素i相同值的位置;
Insert(*L,i,e):線上性表i位置插入元素e;
Delete(*L,i):刪除線性表位置i的元素;
GetLength(*L):獲得當前線性表的長度。
endADT
3、線性表的順序儲存結構
概念:用一段地址連續的儲存單中繼存放區線性表的資料元素。
演算法的C#語言實現
/// <summary> /// 線性表的順序儲存結構 /// </summary> public class SequentialStorageLinearList<T> { //最大存放數量 private int _maxLength; /// <summary> /// 最大儲存數量 /// </summary> public int MaxLength { get { return _maxLength; } } // 當前存放位置 private int _currentLength; private T[] _LinearList; //利用建構函式建立一個數組,用來存放資料 public SequentialStorageLinearList(int maxLength) { if (maxLength <= 0) throw new Exception("The length can not be less than zero."); _maxLength = maxLength; _currentLength = 0; _LinearList = new T[_maxLength]; } /// <summary> /// 判斷線性表是否為空白 /// </summary> /// <returns></returns> public bool IsEmpty() { return _currentLength == 0; } /// <summary> /// 清空所有的元素 /// </summary> public void ClearAll() { if (_currentLength > 0) { /* * 在進階語言.net中,我們可以重新建立一個新的數組,將其指向當前的_linearList *由於是Managed 程式碼,資源不需要手動釋放,會自動釋放 *但是在c語言中,我們需要手動的釋放其佔用的空間(free) */ _LinearList = new T[0]; } } /// <summary> /// 根據 /// </summary> /// <param name="i"></param> /// <returns></returns> public T GetElement(int i) { if (_currentLength == 0 || _currentLength < i || i < 1) throw new Exception("Not find any Element."); T t = _LinearList[i]; return t; } /// <summary> /// 尋找資料中是否存在元素e /// </summary> /// <param name="e"></param> /// <returns></returns> public int IndexOf(T e) { if (_currentLength == 0) throw new Exception("The array is empty."); for (int i = 0; i < _currentLength; i++) { T t = _LinearList[i]; /* * T可能是參考型別,我們暫時的比較方式,不考慮重寫equals */ if (t.Equals(e)) { return i; } } return -1; } /// <summary> /// 在位置i處插入元素e /// </summary> /// <param name="e">待插入的元素e</param> /// <param name="i">插入位置i</param> public void Insert(T e, int i) { //數組已經存滿 if (_currentLength == _maxLength) throw new Exception("The array is full."); //當i位置不在範圍內 if (i < 1 || i > _currentLength + 1) throw new Exception("The location is illegal."); //若插入的資料不在表尾,在需要移動插入位置後面的資料一位 if (i <= _currentLength - 1) { for (int j = _currentLength - 1; j > i; j--) { _LinearList[j + 1] = _LinearList[j]; } } _LinearList[i - 1] = e; _currentLength++; } /// <summary> /// 刪除位元置i處的元素 /// </summary> /// <param name="i">位置i</param> public void Delete(int i) { if (_currentLength == 0) throw new Exception("The array is Empty."); if (i < 1 || i > _currentLength) throw new Exception("The location is illegal."); //刪除位元置i元素後需要將i後面的元素依次遞增一位 if (i < _currentLength) { for (int k = k-1; k < _currentLength; k++) { _LinearList[k - 1] = _LinearList[k]; } } _currentLength--; } }
第三章 線性表(C#實現)