这是实现顺序栈的各种基本运算的算法:
#include <iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
typedef int ElemType;
const int MaxSize=100;
//声明顺序栈的类型
typedef struct{
ElemType data[MaxSize];
int top;
}SqStack;
//栈的初始化
void InitStack(SqStack *&s){
s=(SqStack*)malloc(sizeof(SqStack));
s->top=-1;
}
//栈的销毁
void Destory(SqStack *&s){
free(s);
}
//判断栈是否为空
bool StackEmpty(SqStack *s){
return s->top==-1;
}
//元素进栈
bool Push(SqStack *&s,ElemType e){
if(s->top==MaxSize-1)return false;
s->data[++s->top]=e;
return true;
}
//元素出栈
bool Pop(SqStack *&s,ElemType &e){
if(s->top==-1)return false;
e=s->data[s->top--];
return true;
}
//获取栈顶元素
bool GetTop(SqStack *&s,ElemType &e){
if(s->top==-1)return false;
e=s->data[s->top];
}
int main() {
/*一些简单的操作:
string str;
cin>>str;
int len=str.length();
SqStack* s;
InitStack(s);
for(int i=0;i<len;i++) Push(s,str[i]);
ElemType e;
for(int i=0;i<len/2;i++){
Pop(s,e);
if(str[i]!=e){
cout<<"no";
return 0;
}
}
cout<<"yes";
*/
ElemType a[]={1,3,5,7,9,0,8,6,4,2};
SqStack* s;
InitStack(s);
for(int i=0;i<10;i++)Push(s,a[i]);
for(int i=0;i<10;i++)Pop(s,a[i]);
for(int i=0;i<10;i++)cout<<a[i];
Destory(s);
cout<<endl<<StackEmpty(s)<<endl;
return 0;
}
有不对的地方,请多多指教,谢谢。