- 棧是一種特殊的線性表
棧僅能在線性表的一端進行操做ios
- 棧頂(Top):容許操做的一端
- 棧底(Bottom):不容許操做的一端
- 後進先出 (Last In first Out)
- 建立棧 (Stack())
- 銷燬棧 (~Stack())
- 清空棧 (clear())
- 進棧 (push())
- 出棧 (pop())
- 獲取棧頂元素 (top())
- 獲取棧大小 (size())
template <typename T> class Stack : Object { public: virtual void push(const T &e) = 0; virtual void pop() = 0; virtual T top() const = 0; virtual void clear() = 0; virtual int size() const = 0; };
類模板編程
- 使用原生數組做爲棧的存儲空間
- 使用模板參數決定棧的最大容量
template <typename T, int N> class StaticStack : public Stack<T> { public: StaticStack(); // 初始化成員變量 int capacity() const; protected: T m_space[N]; // 棧存儲空間,N爲模板參數 int m_top; // 棧頂標識 int m_size; // 當前棧的大小 };
文件:Stack.h數組
#ifndef STACK_H #define STACK_H #include "Object.h" namespace DTLib { template <typename T> class Stack : public Object { public: virtual void push(const T &e) = 0; virtual void pop() = 0; virtual T top() const = 0; virtual void clear() = 0; virtual int size() const = 0; }; } #endif // STACK_H
文件:StaticStack.hide
#ifndef STAITCSTACK_H #define STAITCSTACK_H #include "Stack.h" #include "Exception.h" namespace DTLib { template <typename T, int N> class StaticStack : public Stack<T> { public: StaticStack() = default; int capacity() const // O(1) { return N; } void push(const T &e) override // O(1) { if (m_size < N) { m_space[m_top + 1] = e; ++m_top; ++m_size; } else { THROW_EXCEPTION(InvalidOpertionExcetion, "No enough space to push StaticStack ..."); } } void pop() override // O(1) { if (m_size > 0) { --m_top; --m_size; } else { THROW_EXCEPTION(InvalidOpertionExcetion, "No element to pop StaticStack ..."); } } T top() const override // O(1) { if (m_size > 0) { return m_space[m_top]; } else { THROW_EXCEPTION(InvalidOpertionExcetion, "No element in current StaticStack ..."); } } void clear() override // O(1) { m_top = -1; m_size = 0; } int size() const override // O(1) { return m_size; } ~StaticStack() // O(1) { clear(); } protected: T m_space[N]; int m_top = -1; int m_size = 0; }; } #endif // STAITCSTACK_H
文件:main.cppspa
#include <iostream> #include "StaitcStack.h" using namespace std; using namespace DTLib; int main() { StaticStack<int, 5> stack; for (int i=0; i<5; ++i) { stack.push(i); } while (stack.size() > 0) { cout << stack.top() << endl; stack.pop(); } return 0; }
輸出:設計
4 3 2 1 0
- 棧是一種特殊的線性表
- 棧只容許在線性表的一端進行操做
- StaticStack 使用原生數組做爲內存存儲空間
- StaticStack 的最大容量由模板參數決定
以上內容整理於狄泰軟件學院系列課程,請你們保護原創!3d