#include iostream//栈的数组实现using namespace std;#define MAXSIZE 10;templateclass Tclass Stack{public: //默认构造函数 Stack(); Stack(size_t maxElements); Stack(T data[], size_t maxElements); ~Stack(); //入栈 void Push(T data
#include <iostream> //栈的数组实现 using namespace std; #define MAXSIZE 10; template<class T> class Stack { public: //默认构造函数 Stack(); Stack(size_t maxElements); Stack(T data[], size_t maxElements); ~Stack(); //入栈 void Push(T data); //出站并返回 T Pop(); //返回栈顶元素 T Top(); //判断是否为空栈 bool isEmpty(); //栈是否已满 bool isFull(); //清空栈 void Clear(); //获得栈元素个数 size_t GetSize(); private: //栈标指示器 size_t top; //数组 T *arrays; //栈的容量 size_t maxSize; }; template<class T> Stack<T>::Stack() : maxSize(MAXSIZE), top(-1) { arrays = new T[maxSize]; if (arrays == NULL) { cout << "动态分配内存失败"; } } template<class T> Stack<T>::Stack(size_t maxElements) : maxSize(maxElements), top(-1) { arrays = new T[maxSize]; if (arrays == NULL) { cout << "动态分配内存失败"; } } template<class T> Stack<T>::Stack(T data[], size_t maxElements) : maxSize(maxElements), top(-1) { arrays = new T[maxSize];//创建存储栈的数组 for (size_t i = 0; i < maxSize; i++) { arrays[i] = data[i]; } top += maxSize; } template<class T> Stack<T>::~Stack() { delete[] arrays; } template<class T> void Stack<T>::Push(T data) { if (isFull()) { throw runtime_error("Full stack"); } else { top++;//指向栈顶 arrays[top] = data; } } template<class T> T Stack<T>::Pop() { if (isEmpty()) { throw runtime_error("No elements in the stack"); } else { T data = arrays[top]; top--; return data; } } template<class T> T Stack<T>::Top() { if (isEmpty()) { throw runtime_error("No elements in the stack"); } else { return arrays[top]; } } template<class T> bool Stack<T>::isEmpty() { return top == -1; } template<class T> bool Stack<T>::isFull() { return top == maxSize - 1; } template<class T> void Stack<T>::Clear() { while (Top != -1) { Top--; } } template<class T> size_t Stack<T>::GetSize() { return top + 1; } int main() { try//异常捕获 { int a[6] = { 1, 2, 3, 4, 5, 6 }; Stack<int> s(a, 6); s.Pop(); s.Push(7); for (int i = 0; i < 6; i++) { cout << s.Pop() << " "; } cout << endl; } catch (exception e) { cout << e.what() << endl; } system("pause"); return 0; }
来源:c++ 栈的数组实现