首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

資料結構 (C#):順序表(動態陣列)完整實作

     編輯:關於C語言

順序表特性

  • 邏輯相鄰元素物理相鄰,索引存取快
  • 插入/刪除需移動元素,效率較低
  • 儲存區連續,擴容需複製原元素

完整程式碼

namespace Xianfen.Net.DataStructure {
    public class SequentialList<T> : ILinearList<T> {
        private T[] m_List;
        private int m_Count, m_Capacity;
        public int Count { get { return m_Count; } }
        public bool IsEmpty { get { return m_Count == 0; } }
        public SequentialList() : this(16) {}
        public SequentialList(int capacity) { m_Count = 0; m_Capacity = capacity; m_List = new T[m_Capacity]; }
        public void Add(T t) { InsertAt(t, m_Count); }
        public void AddHead(T t) { InsertAt(t, 0); }
        public void AddTail(T t) { Add(t); }
        public void Clear() { m_Count = 0; }
        public int Find(T t) { for (int i = 0; i < m_Count; i++) if (m_List[i].Equals(t)) return i; return -1; }
        public T GetAt(int pos) { if (pos >= m_Count || pos < 0) throw new IndexOutOfRangeException("pos"); return m_List[pos]; }
        public T GetHead() { return m_List[0]; }
        public T GetTail() { return m_List[m_Count - 1]; }
        public void InsertAt(T t, int pos) { /* 含擴容、元素後移、插入 */ }
        public void RemoveAll() { Clear(); }
        public void RemoveAt(int pos) { /* 元素前移、計數遞減 */ }
        public void RemoveHead() { RemoveAt(0); }
        public void RemoveTail() { RemoveAt(m_Count - 1); }
        public void SetAt(int pos, T t) { if (pos >= m_Count || pos < 0) throw new IndexOutOfRangeException("pos"); m_List[pos] = t; }
        private void EnsureCapacity() { if (m_Count + 1 > m_Capacity) { m_Capacity *= 2; if (m_Count + 1 > m_Capacity) m_Capacity = m_Count + 1; T[] tmp = new T[m_Capacity]; for (int i = 0; i < m_Count; i++) tmp[i] = m_List[i]; m_List = tmp; } }
        public IEnumerator<T> GetEnumerator() { for (int i = 0; i < m_Count; i++) yield return m_List[i]; }
        IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
    }
}

擴容策略參考 StringBuilder:容量不足時加倍。下一篇介紹單向鏈結串列。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved