【c++】栈的实现

来源:互联网 发布:vnc 客户端 windows 编辑:程序博客网 时间:2024/05/02 05:06

栈(stack)又名堆栈,它是一种运算受限的线性表。其限制是仅允许在表的一端进行插入和删除运算。这一端被称为栈顶,相对地,把另一端称为栈底。向一个栈插入新元素又称作进栈、入栈或压栈,它是把新元素放到栈顶元素的上面,使之成为新的栈顶元素;从一个栈删除元素又称作出栈或退栈,它是把栈顶元素删除掉,使其相邻的元素成为新的栈顶元素。

#include<iostream>#include <cstdlib>using namespace std;class SqStack{public:SqStack();~SqStack();bool isEmpty();void pushInt(int x);int popInt();int getTop();void display();private:enum{MaxSize=100};int data[MaxSize];int top;};SqStack::SqStack(){top=-1;}SqStack::~SqStack(){}bool SqStack::isEmpty()//判断栈为空{return(top==-1);}void SqStack::pushInt(int x)//元素进栈{if(top==MaxSize-1){cout<<"栈上溢出!"<<endl;}else{++top;data[top]=x;}}int SqStack::popInt()//退栈{int tmp=0;if(top==-1){cout<<"栈已空!"<<endl;}else{tmp=data[top--];}return tmp;}int SqStack::getTop()//获得栈顶元素{int tmp=0;if(top==-1){cout<<"栈空!"<<endl;}else{tmp=data[top];}return tmp;}void SqStack::display()//打印栈里元素{cout<<"栈中元素:"<<endl;for(int index=top;index>=0;--index){cout<<data[index]<<endl;}}int main(){SqStack st;cout<<"栈空:"<<st.isEmpty()<<endl;for(int i=1;i<10;i++){st.pushInt(i);}st.display();cout<<"退一次栈"<<endl;st.popInt();cout<<"栈顶元素:"<<st.getTop()<<endl;st.popInt();st.display();system("pause");return 0;}


0 0
原创粉丝点击