实现栈的初始化,进栈,出栈,取栈顶,判断是否空栈,销毁栈
#include<iostream> #include<cstdio> #include<malloc.h> using namespace std; typedef int ElemType; const int MaxSize=50; typedef struct { ElemType data[MaxSize]; int top; }SqStack; void InitStack(SqStack *&s) { s=(SqStack *)malloc(sizeof(SqStack)); s->top=-1; } void CreateStack(SqStack *&s,int a[],int n) { s=(SqStack *)malloc(sizeof(SqStack)); for(int i=0;i<n;i++) s->data[i]=a[i]; s->top=n; } bool EmptyStack(SqStack *s) { return s->top==-1; } void Destroy(SqStack *&s) { free(s); } bool disp(SqStack *&s) { if(s->top==-1) return false; for(int i=0;i<s->top;i++) cout<<s->data[i]<<" "; cout<<endl; return true; } bool Push(SqStack *&s,int e) { if(s->top==MaxSize) return false; s->top++; s->data[s->top-1]=e; return true; } bool Gettop(SqStack *&s,int &e) { if(s->top==-1) return false; e=s->data[s->top-1]; return true; } bool Pop(SqStack *s,int &e) { if(s->top==-1) return false; e=s->data[s->top-1]; s->top--; return true; } int main() { SqStack *s; ElemType a[MaxSize]; InitStack(s); int n,i,e; cout<<"请输入一个栈的长度n"<<endl; cin>>n; cout<<"请输入栈中的数字: "; for(i=0;i<n;i++) cin>>a[i]; CreateStack(s,a,n); cout<<"栈s: "; disp(s); Gettop(s,e); cout<<endl<<"栈顶的元素是 : "<<e<<endl; cout<<"请输入你想进栈的元素 : "; cin>>e; Push(s,e); cout<<"栈s: "; disp(s); Pop(s,e); cout<<endl<<"栈顶的元素是 : "<<e<<endl; cout<<"栈顶出栈之后的s是: "; disp(s); i=EmptyStack(s); if(i) cout<<endl<<"这是一个空栈"<<endl; else cout<<endl<<"这不是一个空栈"<<endl; Destroy(s); }