C++ 堆栈
#ifndef SEQSTACK_H #define SEQSTACK_H #include<iostream> using namespace std; class SeqStack{ public: SeqStack(int size=defaultMaxsize){ if(size>0){ maxSize=size; data=new int[maxSize]; for(int i=0;i<maxSize;++i){ data[i]=0; } top=-1; } } //判断栈空算法 bool Empty_SeqStack(SeqStack *s); //入栈算法 bool Push_SeqStack(SeqStack *s,int x); //出栈算法 bool Pop_SeqStack(SeqStack *s,int *x); //取栈顶元素 bool Top_SeqStack(SeqStack *s,int *x); private: //默认长度 const static int defaultMaxsize=10; //最大长度 int maxSize; //堆栈元素 int *data; //栈顶元素位置 int top; }; bool SeqStack::Empty_SeqStack(SeqStack *s){ if(s->top==-1){ return true; } return false; } bool SeqStack::Push_SeqStack(SeqStack *s,int x){ if(s->top<maxSize-1){ s->data[++s->top]=x; return true; } return false; } bool SeqStack::Pop_SeqStack(SeqStack *s,int *x){ if(s->Empty_SeqStack(s)){ return false; }else{ *x=s->data[s->top--]; return true; } } bool SeqStack::Top_SeqStack(SeqStack *s,int *x){ if(s->Empty_SeqStack(s)){ return false; }else{ *x=s->data[s->top]; return true; } } #endif
#include<iostream> #include"SeqStack.h" using namespace std; int main(){ int data[10]={0,1,2,3,4,5,6,7,8,9},a,b; int *t=&a,*p=&b; SeqStack *s=new SeqStack(); for(int i=0;i<=5;++i){ s->Push_SeqStack(s,i); } if(s->Empty_SeqStack(s)){ cout<<"入栈失败"<<endl; }else{ s->Top_SeqStack(s,t); cout<<"入栈成功,栈顶元素是:"<<*t<<endl; } if(s->Pop_SeqStack(s,p)){ s->Top_SeqStack(s,t); cout<<"出栈成功,移除栈顶元素是:"<<*p<<"新的栈顶元素是:"<<*t<<endl; } return 0; }