多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
栈的实现,包含的函数有Top(), Push(), Pop(). 简单易懂的代码~ 实现代码: ~~~ #include "iostream" #include "cstdio" #include "cstring" #include "algorithm" using namespace std; template <class T> class Stack { public: virtual bool IsEmpty() const = 0; // 判断栈是否为空 为空则返回true virtual bool IsFull() const = 0; // 判断栈是否满 满则返回true virtual bool Top(T &x) const = 0; // 返回栈顶元素 操作成功则返回true virtual bool Push(T x) = 0; // 入栈 操作成功则返回true virtual bool Pop() = 0; // 出栈 操作成功则返回true virtual void Clear() = 0; // 清除栈中所有元素 /* data */ }; template <class T> class SeqStack: public Stack<T> { public: SeqStack(int mSize); ~SeqStack() { delete []s; } bool IsEmpty() const { return top == 1; } bool IsFull() const { return top == maxTop; } bool Top(T &x) const; bool Push(T x); bool Pop(); void Clear() { top = -1; } /* data */ private: int top, maxTop; // 栈顶指针 最大栈顶指针 T *s; }; template <class T> SeqStack<T>::SeqStack(int mSize) { maxTop = mSize - 1; s = new T[mSize]; top = 1; } template <class T> bool SeqStack<T>::Top(T &x) const { if(IsEmpty()) { cout << "Stack is empty" << endl; return false; } x = s[top]; return true; } template <class T> bool SeqStack<T>::Push(T x) { if(IsFull()) { cout << "Stack is full" << endl; return false; } s[++top] = x; return true; } template <class T> bool SeqStack<T>::Pop() { if(IsEmpty()) { cout << "Stack is empty" << endl; return false; } top--; return true; } int main(int argc, char const *argv[]) { SeqStack<int> s(5); for(int i = 0; i < 3; ++i) s.Push(i); // s包含0 1 2 int x; if(s.Top(x)) cout << "The top of s is " << x << endl; if(s.Push(x)) cout << "Push successfully" << endl; if(s.Pop()) cout << "Pop successfully" << endl; s.Clear(); return 0; } ~~~