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:容量不足時加倍。下一篇介紹單向鏈結串列。