1、 将之前定义的栈类和队列类都实现成模板类
#include <iostream>using namespace std;#define MAX 128template<typename T>class Stack
{
public://构造函数Stack();//析构函数~Stack();//拷贝构造函数Stack(const Stack &other);//入栈int push(T e);//出栈int pop();//清空栈void clear();//判空bool empty();//判满bool full();//获取栈顶元素T topdata();//求栈的大小int size();
private:T*data;int top;};template<typename T>
//构造函数
Stack<T>::Stack():data(new T[MAX]),top(-1){cout<<"构造函数"<<endl;}
template<typename T>
//析构函数
Stack<T>::~Stack()
{delete []data; //释放指针空间cout<<"析构函数"<<endl;
}
template <typename T>//拷贝构造函数
Stack<T>::Stack(const Stack &other):data(new T[MAX]),top(other.top)
{std::copy(other.data,other.data+MAX,data);cout<<"拷贝函数"<<endl;
}//入栈
template <typename T>
int Stack<T>::push(T e){if(Stack<T>::full()){cout<<"栈满,无法入栈;"<<endl;return 0;}data[++top]=e;cout<<data[top]<<"已入栈"<<endl;return 1;
}
//出栈
template <typename T>
int Stack<T>::pop(){if(Stack<T>::empty()){cout<<"栈空,无法出栈;"<<endl;return 0;}cout<<data[top--]<<"已出栈"<<endl;return 1;
}
//清空栈
template <typename T>
void Stack<T>::clear(){cout<<"栈已清空"<<endl;while(!Stack::empty()){Stack::pop();}
}
//判空
template <typename T>
bool Stack<T>::empty(){return -1 == top;
}
//判满
template <typename T>
bool Stack<T>::full(){return MAX-1 == top;
}
//获取栈顶元素
template <typename T>
T Stack<T>::topdata(){cout<<"栈顶元素为:";return data[top];
}
//求栈的大小
template <typename T>
int Stack<T>::size(){cout<<this<<"栈的大小为:";return top+1;
}int main()
{Stack<string> s;s.push("haha");s.push("wowo");s.push("nini");s.push("tata");s.push("lala");s.push("hehe");cout<<s.size()<<endl;Stack<string> s2=s;cout<<s2.size()<<endl;Stack<string> s3=s2;cout<<s3.size()<<endl;s3.pop();s3.pop();s3.pop();cout<<s3.topdata()<<endl;s3.clear();s3.pop();cout<<s3.size()<<endl;cout<<s.size()<<endl;return 0;
}
2、思维导图