1. 程式人生 > >棧的順序儲存結構 -- C++使用類模板實現

棧的順序儲存結構 -- C++使用類模板實現

棧是先進後出的線性表。即限定只能在表的一段進行插入和刪除操作的線性表。

棧結構在計算機中有廣泛的應用。常見的軟體的”撤銷”和”恢復”功能就是用棧實現的。

棧的順序儲存結構示例程式碼

template<typename T>
class SqStack
{
public:
    SqStack(int k = 1);
    ~SqStack(){ delete[]m_base; }
    void Clear() { m_top = m_base; }
    bool Empty() const { return m_top == m_base; }
    int
Length() const { return m_top - m_base; } T Top() const; bool Push(T elem); bool Pop(); void Display(); private: T *m_base; //棧儲存空間的基址 T *m_top; //棧頂指標 int m_size; //棧當前的儲存容量 }; template<typename T> SqStack<T>::SqStack(int k = 1) { m_base = new T[k]; if
(nullptr == m_base) { cout << "申請空間失敗" << endl; return; } m_top = m_base; m_size = k; } template<typename T> T SqStack<T>::Top() const //返回棧頂元素 { if (m_top > m_base) //棧不為空 { return *(m_top-1); //返回棧頂元素 為什麼要減1? <== [base, top)
} else { return false; } } template<typename T> bool SqStack<T>::Push(T elem) { if (m_top - m_base == m_size) //棧滿,需要重新申請空間 { T *newbase = new T[m_size * 2]; if (nullptr == newbase) { return false; } for (int i = 0; i < m_top - m_base; ++i) //將原本的資料複製到新的記憶體中 { *(newbase + i) = *(m_base + i); } delete []m_base; //釋放舊資料的記憶體 m_base = newbase; //將基址指標指向新的記憶體 m_top = m_base + m_size; //將棧頂指標指向新的棧頂地址 m_size *= 2; //更新棧頂大小 } *m_top = elem; //將元素賦給棧頂 m_top++; //棧頂指標自增 return true; } template<typename T> bool SqStack<T>::Pop() { if (m_top == m_base) //判斷棧是否為空 { return false; } --m_top; //若不為空,將棧頂指標自減1 return true; } template<typename T> void SqStack<T>::Display() { T *temp = m_base; while (temp < m_top) { cout << *temp++ << " "; } cout << endl; }

測試程式:

int main()
{
    SqStack<int> s;
    cout << s.Empty() << endl;
    for (int i = 1; i < 10; ++i)
    {
        s.Push(i);
    }

    cout << s.Top() << endl;

    s.Pop();

    s.Display();

    system("pause");
    return 0;
}

執行結果:
這裡寫圖片描述