链式栈

来源:互联网 发布:linux自动挂载 编辑:程序博客网 时间:2024/05/22 17:05
#ifndef LINKEDSTACK_H#define LINKEDSTACK_Htemplate<class T> class LinkedStack;template<class T>class ChainNode{friend class LinkedStack<T>;private:ChainNode(const T& theData, ChainNode *n = 0): data(theData), link(n) {}T data;ChainNode<T> *link;};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 "Stack is empty.Connot delete.";ChainNode<T> *delNode = top;top = top->link;delete delNode;}template<class T>void LinkedStack<T>::MakeEmpty(){while(!IsEmpty())Pop();}#endif 
#include <iostream>#include "LinkedStack.h"using namespace std;int main(){LinkedStack<int> s;s.Push(6);cout << s.Top() << endl;s.Push(3);cout << s.Top() << endl;s.Pop();cout << s.Top() << endl;return 0;}


0 0
原创粉丝点击