使用链表做的堆栈
先进后出
栈的主要三个操作
- Push
- Pop
- Top
-
#ifndef __LinkStack_H__ #define __LinkStack_H__ #include <iostream> template <class T> class LinkStack; template <class T> class LinkNode { friend class LinkStack<T>; //有元函数 private: LinkNode(const T &thedata,LinkNode * n=0):data(thedata),link(n){} T data; //节点数据 LinkNode<T> *link; //节点指针 指向下一个 }; template <class T> class LinkStack { private: LinkNode<T> *top; public: LinkStack():top(0){} //构造函数 ~LinkStack(){MakeEmpty();} //析构函数 bool IsEmpty() const; //查看是否空 void Push(const T& e); //压栈 void Pop(); T& Top()const; //返回栈顶的数据 void MakeEmpty(); }; template<class T> void LinkStack<T>::MakeEmpty() { while(!(this->IsEmpty())) Pop(); } template <class T> bool LinkStack<T>::IsEmpty()const { return top==0; } template<class T> void LinkStack<T>::Push(const T&e) { top=new LinkNode<T>(e,top); //放入数据 ,并且top指向放入数据的那个数 } template<class T> T& LinkStack<T>::Top() const //查看栈顶的数据 { if(this->IsEmpty()) throw "Stack is Empty"; return top->data; //返回数据 } template<class T> void LinkStack<T>::Pop() { if(this->IsEmpty()) throw "Stack is Empty can not delete"; LinkNode<T> *p=top; //定义一个指针 保存top top=top->link; //移动一个节点 delete p; } #endif // __LinkStack_H__
#include <iostream> #include "LinkStack.h" using namespace std; int main() { LinkStack<int> p; p.Push(10); cout<<p.Top()<<endl; p.Push(12); cout<<p.Top()<<endl; p.Push(13); // cout << "Hello world!" << endl; cout<<p.Top()<<endl; p.Pop(); cout<<p.Top()<<endl; p.Pop(); cout<<p.Top()<<endl; return 0; }