数据结构(4) 顺序栈 c++ 模板实现

来源:互联网 发布:淘宝子账号怎么设置 编辑:程序博客网 时间:2024/06/17 00:02

顺序栈       

栈的顺序存储结构简称为顺序栈,它是运算受限的顺序表。实现同样是数组。

//SeqStack.htemplate <typename Type> class SeqStack{private:int m_TopofStack;Type *m_pbase;int m_nMaxsize;public:SeqStack(int size=10):m_TopofStack(-1),m_nMaxsize(size){m_pbase=new(nothrow) Type[size];//new的nothrow版本,失败则返回一个空指针if (m_pbase==NULL){cout<<"error!"<<endl;exit(-1);}};//将m_TopofStack=-1是为了适应数组下标的命名习惯,为0时就是有一个元素~SeqStack(){   delete []m_pbase;}public:void ClearStack();bool Push(const Type item);//压栈Type Pop();//出栈Type Peek() const;//获得头元素void Print();//void ReNew(int plussize=10);int Length();bool IsEmpty(){return m_TopofStack==-1;}bool IsFull(){return m_TopofStack==m_nMaxsize-1;}//因为m_TopofStack比实际的元素数量小1};template <typename Type> void SeqStack<Type>::ClearStack(){//while(m_TopofStack>=0);//m_pbase[m_TopofStack--]=NULL;m_TopofStack=-1;}template <typename Type> int SeqStack<Type>::Length(){return m_TopofStack+1;}template <typename Type> bool SeqStack<Type>::Push(const Type item){if(SeqStack<Type>::IsFull()){cout<<"The stack is full!"<<endl;return false;}m_pbase[++m_TopofStack]=item;return true;}template <typename Type> Type SeqStack<Type>::Pop(){if(SeqStack<Type>::IsEmpty()){cout<<"Stack is empty!"<<endl;return NULL;}    return m_pbase[m_TopofStack--];}template <typename Type> Type SeqStack<Type>::Peek() const{if(SeqStack<Type>::IsEmpty()){cout<<"Stack is empty!"<<endl;return NULL;}return m_pbase[m_TopofStack];}template <typename Type> void SeqStack<Type>::Print(){for(int i=0;i<=m_TopofStack;i++)cout<<m_pbase[i]<<endl;}

测试代码:

//SeqStack.cpp#include "stdafx.h"#include "SeqStack.h"#include <iostream>using namespace std;int _tmain(int argc, _TCHAR* argv[]){SeqStack<int> stack;for(int i=0;i<10;i++)stack.Push(i);stack.Print();stack.Push(88);cout<<stack.Pop()<<endl;stack.Print();stack.ClearStack();stack.Print();stack.Pop();stack.Print();return 0;}



原创粉丝点击