GKHacks Blog

栈的实现,包含的函数有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; // 判断栈是否为空 为空则返回truevirtual bool IsFull() const = 0; // 判断栈是否满 满则返回truevirtual bool Top(T &x) const = 0; // 返回栈顶元素 操作成功则返回truevirtual bool Push(T x) = 0; // 入栈 操作成功则返回truevirtual bool Pop() = 0; // 出栈 操作成功则返回truevirtual 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 2int 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;}

版权声明:本文为博主原创文章,未经博主允许不得转载。

,往往教导我们大家要好好学习天天向上,要永不言弃坚持到底百折不挠宁死不屈,

GKHacks Blog

相关文章:

你感兴趣的文章:

标签云: