静态数组实现栈

来源:互联网 发布:淘宝自己制作模板 编辑:程序博客网 时间:2024/05/22 01:44

 VS2005运行通过,如有问题,请各位大牛指正。

/*静态栈的条件栈顶初始值:top=-1;栈顶:总是指向刚刚压入的值栈空:top=-1栈满:top=Max-1入栈: data[++top] = NewItem;出栈:newItem = data[top--];*/#include <iostream>using namespace std;const int Max = 50;template<class Type>class Stack{private:Type data[Max];int top;public:Stack();Stack(const Stack<Type>& otherStack);~Stack();Stack<Type> operator=(const Stack<Type>& otherStack);void initStack();bool isEmptyStack() const;bool IsFullStack() const;;void destoryStack();void pop(Type& data);void push(Type data);};template<class Type>Stack<Type>::Stack(){top=-1;}template<class Type>Stack<Type>::Stack(const Stack<Type>& otherStack){top = otherStack.top;if (!otherStack.isEmptyStack()){for (int i=0;i<=top;i++){data[i] = otherStack.data[i];}}}template<class Type>Stack<Type>::~Stack(){}template<class Type>Stack<Type> Stack<Type>::operator=(const Stack<Type>& otherStack){if (this != &otherStack){if (!otherStack.isEmptyStack()){top = otherStack.top;for (int i=0;i<=top;i++){data[i] = otherStack.data[i];}}}return *this;}template<class Type>void Stack<Type>::initStack(){top=-1;}template<class Type>bool Stack<Type>::isEmptyStack() const{return (top==-1);}template<class Type>bool Stack<Type>::IsFullStack() const{return (top==Max-1);//top表示指针位置,最大为Max-1}template<class Type>void Stack<Type>::destoryStack(){top=-1;}template<class Type>void Stack<Type>::pop(Type& NewItem){if (isEmptyStack()){cout<<"栈空"<<endl;}else{NewItem = data[top--];}}template<class Type>void Stack<Type>::push(Type NewItem){if (IsFullStack()){cout<<"栈满!"<<endl;}else{data[++top]= NewItem;}}int main(){Stack<int> s;Stack<int> s1;s1=s;int a[4]={1,2,3,4};for (int i=0;i<4;i++){s1.push(a[i]);}for (int i=0;i<4;i++){int temp;s1.pop(temp);cout<<temp<<endl;}system("pause");return 0;}