数据结构之——基于链表的栈的C++模板实现
//节点的结构 template<typename T> struct node { T data; node<T>* next; node():next(nullptr){}; node(T t):data(t),next(nullptr){}; } //模板类构造栈类 template<typename T> Class MyStack { public: MyStack(); void push(T &x); T top(); void pop(); int counts(); bool empty(); ~MyStack(); private: int count; node<T>* head; } template<typename T> void MyStack<T>::push(T &x) { node<T>* pnode= new node<T>(x);//申请空间 pnode->next=head->next; head->next=pnode; count++; } template<typename T> bool MyStack<T>::empty() { return count==0; } template<typename T> T MyStack<T>::top() { if(!empty()) return head->next->dada; } template<typename T> void MyStack<T>::pop() { if(!empty()) { node<T>* del=head->next; head->next=head->next->next; delete del; count--; } } template<typename T> int MyStack<T>::counts() { return count; }