这种使用原生数组作为存储容器的栈也简称顺序栈。
添加Stack.h文件:
1 #ifndef STACK_H 2 #define STACK_H 3 4 #include "Object.h" 5 6 namespace DTLib 7 { 8 9 template < typename T > 10 class Stack : public Object 11 { 12 public: 13 virtual void push(const T& e) = 0; 14 virtual void pop() = 0; 15 virtual T top() const = 0; 16 virtual void clear() = 0; 17 virtual int size() const = 0; 18 }; 19 20 } 21 22 #endif // STACK_H
添加StaticStack.h文件:
1 #ifndef STATICSTACK_H 2 #define STATICSTACK_H 3 4 #include "Stack.h" 5 #include "Exception.h" 6 7 namespace DTLib 8 { 9 10 template < typename T, int N > 11 class StaticStack : public Stack<T> 12 { 13 protected: 14 T m_space[N]; 15 int m_top; 16 int m_size; 17 public: 18 StaticStack() 19 { 20 m_top = -1; 21 m_size = 0; 22 } 23 24 int capacity() const 25 { 26 return N; 27 } 28 29 void push(const T& e) 30 { 31 if( m_size < N ) 32 { 33 m_space[m_top + 1] = e; //先赋值,保证异常安全 34 m_top++; 35 m_size++; 36 } 37 else 38 { 39 THROW_EXCEPTION(InvalidOperationException, "No space in current stack ..."); 40 } 41 } 42 43 void pop() 44 { 45 if( m_size > 0 ) 46 { 47 m_top--; 48 m_size--; 49 } 50 else 51 { 52 THROW_EXCEPTION(InvalidOperationException, "No element in current stack ..."); 53 } 54 } 55 56 T top() const 57 { 58 if( m_size > 0 ) 59 { 60 return m_space[m_top]; 61 } 62 else 63 { 64 THROW_EXCEPTION(InvalidOperationException, "No element in current stack ..."); 65 } 66 } 67 68 void clear() 69 { 70 m_top = -1; 71 m_size = 0; 72 } 73 74 int size() const 75 { 76 return m_size; 77 } 78 }; 79 80 } 81 82 #endif // STATICSTACK_H
测试程序如下:
1 #include <iostream> 2 #include "StaticStack.h" 3 4 using namespace std; 5 using namespace DTLib; 6 7 8 int main() 9 { 10 StaticStack<int, 5> stack; 11 12 for(int i = 0; i < 5; i++) 13 { 14 stack.push(i); 15 } 16 17 while( stack.size() > 0 ) 18 { 19 cout << stack.top() << endl; 20 stack.pop(); 21 } 22 23 return 0; 24 }
运行结果如下:
小结:
原文地址:https://www.cnblogs.com/wanmeishenghuo/p/9657059.html
时间: 2024-10-17 19:46:23