C++类模板 实现顺序栈

来源:互联网 发布:北京 纹眉 知乎 编辑:程序博客网 时间:2024/05/16 23:32

栈的顺序存储结构称为顺序栈,下面是顺序栈的实现:

/*Filename: SeqStack.hDescription: About the sequence of stackDate: November 15, 2012*/#ifndef SEQSTACK_H#define SEQSTACK_H#include <iostream>using namespace std;const int StackSize = 10;//顺序栈类定义template<class T>class SeqStack{public:SeqStack(){top = -1;}~SeqStack(){}public:void Push(T x); //将元素x入栈T Pop();        //栈顶元素出栈T GetTop();//读取栈顶元素bool Empty();void PrintStack();//打印栈内元素private:T data[StackSize];int top;};//顺序栈类实现template<class T>void SeqStack<T>::Push(T x){if (top == StackSize-1){throw "上溢";}data[++top] = x;}template<class T>T SeqStack<T>::Pop(){if (top == -1){throw "下溢";}T x = data[top--];return x;}template<class T>T SeqStack<T>::GetTop(){if (top != -1){return data[top];}}template<class T>bool SeqStack<T>::Empty(){if (top == -1 ){return true ;}return false;}template<class T>void SeqStack<T>::PrintStack(){if (!Empty()){int temp = top;while (temp != -1){cout << data[temp] << " ";temp--;}}cout << endl;}#endif#include "SeqStack.h"int main(){SeqStack<int> Ss;Ss.Push(2);Ss.Push(5);Ss.Push(7);Ss.Push(9);Ss.PrintStack();cout << "-------------------------" << endl;cout << "获得栈顶元素:" << Ss.GetTop() << endl;cout << "栈顶元素出栈:" << Ss.Pop() << endl;Ss.PrintStack();system("pause");return 0;}


 有什么问题或错误的地方请大家指出来,互相学习,谢谢.........

原创粉丝点击