practice2.h文件
#ifndef PRACTICE2_H_INCLUDED #define PRACTICE2_H_INCLUDED template<class T> class LinkedStack; template<class T> class ChainNode//栈里面的每个节点 { friend class LinkedStack<T>; private: T data; ChainNode<T> *link; ChainNode(const T& theData,ChainNode *n=0):data(theData),link(n) {} }; template<class T> class LinkedStack { public: LinkedStack():top(0) {} ~LinkedStack() {MakeEmpty();} bool IsEmpty() const; T& Top() const; void Push(const T& e); void Pop(); void MakeEmpty(); private: ChainNode<T> *top; }; template<class T> bool LinkedStack<T>::IsEmpty() const { return top==0; } template <class T> void LinkedStack<T> ::Push(const T &e) { top=new ChainNode<T>(e,top); } template <class T> T& LinkedStack<T>::Top() const { if(this->IsEmpty()) { throw "Stack is Empty"; } return top->data; } template<class T> void LinkedStack<T>::Pop() { if(this->IsEmpty()) throw"is Empty"; ChainNode<T> *delNode=top; top=top->link; delete delNode;//如果不删除的话会产生内存泄漏 和push的new对应 } template<class T> void LinkedStack<T>::MakeEmpty() { while(!IsEmpty()) Pop(); } #endif // PRACTICE2_H_INCLUDED
practice1.cpp
#include<iostream> #include "practice2.h" using namespace std; int main() { LinkedStack<int> s; s.Push(10); cout<<s.Top()<<endl; s.Push(20); cout<<s.Top()<<endl; s.Pop(); cout<<s.Top()<<endl; return 0; }