当前位置:首页 > 通信资讯 > 正文

c++顺序栈的实现代码(C++顺序栈)

顺序栈:利用一组连续的存储单元依次存放自栈底到栈顶的数据元素;由于栈顶元素是经常变动的,所以附设top指示栈顶元素在顺序表中的位置,同时也需要知道顺序栈存储空间的起始位置,因此还需设定一个base指针用来指示栈空间的起始位置。

一般约定top指针指向栈顶元素的下一个位置,即新数据元素将要插入得位置。

下面我们使用模板简单实现一个顺序栈:

SeqStack.h

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 template<typename Type> class SeqStack{ public: SeqStack(int sz):m_ntop(-1),m_nMaxSize(sz){ m_pelements=new Type[sz]; if(m_pelements==NULL){ cout<<"Application Error!"<<endl; exit(1); } } ~SeqStack(){ delete[] m_pelements; } public: void Push(const Type item); //push data Type Pop(); //pop data Type GetTop() const; //get data void Print(); //print the stack void MakeEmpty(){ //make the stack empty m_ntop=-1; } bool IsEmpty() const{ return m_ntop==-1; } bool IsFull() const{ return m_ntop==m_nMaxSize-1; } private: int m_ntop; Type *m_pelements; int m_nMaxSize; }; template<typename Type> void SeqStack<Type>::Push(const Type item){ if(IsFull()){ cout<<"The stack is full!"<<endl; return; } m_pelements[++m_ntop]=item; } template<typename Type> Type SeqStack<Type>::Pop(){ if(IsEmpty()){ cout<<"There is no element!"<<endl; exit(1); } return m_pelements[m_ntop--]; } template<typename Type> Type SeqStack<Type>::GetTop() const{ if(IsEmpty()){ cout<<"There is no element!"<<endl; exit(1); } return m_pelements[m_ntop]; } template<typename Type> void SeqStack<Type>::Print(){ cout<<"bottom"; for(int i=0;i<=m_ntop;i++){ cout<<"--->"<<m_pelements[i]; } cout<<"--->top"<<endl<<endl<<endl; }

Main.cpp

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 #include<iostream> using namespace std; #include "SeqStack.h" int main(){ SeqStack<int> stack(10); int init[10]={1,2,6,9,0,3,8,7,5,4}; for(int i=0;i<10;i++){ stack.Push(init[i]); } stack.Print(); stack.Push(88); cout<<stack.Pop()<<endl; stack.Print(); stack.MakeEmpty(); stack.Print(); stack.Pop(); return 0; }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/fanyun_01/article/details/77618385

如果您对该产品感兴趣,请填写办理(客服微信:xiaoxiongyidong)

为您推荐:

发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。