#ifndef LINKEDSTACK_H #define LINKEDSTACK_H #include #include using namespace std; template struct StackNode{ T data; StackNode *link; StackNode(T d = 0, StackNode *next = NULL) :link(next), data(d){} }; template class LinkedStack{ private: StackNode *top; public: LinkedStack() :top(NULL){}//无头结点 ~LinkedStack(){ makeEmpty(); } void Push(const T &x); bool Pop(T &x); bool getTop(T &x)const; int getSize()const; bool IsEmpty()const{ return top == NULL; } bool IsFull()const{ return false; } void makeEmpty(); friend ostream& operator << (ostream &os, LinkedStack &s) { os << "Stack Size: " << s.getSize() << endl; StackNode *p = s.top; int i = 0; while (p){ os << ++i << ": " << p->data << endl; p = p->link; } return os; } }; template void LinkedStack::makeEmpty(){ StackNode *p; while (top){//最后top为NULL p = top; top = top->link; delete p; } } template void LinkedStack::Push(const T &x){ top = new StackNode(x, top); assert(top); } template bool LinkedStack::Pop(T &x){ if (IsEmpty()){ return false; } StackNode *p = top; top = top->link; x = p->data; delete p; return true; } template bool LinkedStack::getTop(T &x)const{ if (IsEmpty()) return false; x = top->data; return true; } template int LinkedStack::getSize()const{ StackNode *p = top; int k = 0; while (p){ p = p->link; k++; } return k; } #endif