代码

#define ElemType int
#define Status int
#define OK 0
#define OVERFLOW -1
#define ERROR -1
#define MAXSIZE 100
using namespace std;
#include<bits/stdc++.h>
//结构定义 
typedef struct {
    ElemType *base; //栈底指针 
    ElemType *top; //栈顶指针 
    int stacksize; //最大容量
}SqStack; 
//初始化栈 
Status InitStack(SqStack &S) {
    S.base = new ElemType[MAXSIZE]; 
    if(!S.base) return ERROR;
    S.top = S.base;
    S.stacksize = MAXSIZE;
    return OK;
}
//入栈 
Status Push(SqStack &S,ElemType e){
    //判断栈满了没有
    if(S.top - S.base == S.stacksize )  return ERROR;
    *S.top = e; //赋值 
    S.top++; //指针后移
    return OK;     
}

//出栈 通过e返回栈顶元素 
Status Pop(SqStack &S,ElemType &e){
    
    //判断到栈底没有
    if(S.top==S.base)  return ERROR;
    S.top--;
    e = *S.top;
//    e =*(--S.top);
    return OK;
}

//取栈顶元素
ElemType GetTop(SqStack S) { 
    //空栈 没东西 
    if(S.top==S.base) return ERROR;
    return *(--S.top); 
}

int main() {
    SqStack S;
    InitStack(S);
    
    cout << "入栈0 1 2 3 4" << endl;
    for(int i =0;i<5;i++) {
        //入栈 
        Push(S,i);
    }
    //获取栈顶元素 
    ElemType e= GetTop(S);
    cout << "栈顶元素是:" <<e << endl;
    
    cout << "出栈" << endl;
    for(int i =0;i<5;i++) {
        //入栈 
        Pop(S,e);
        cout << e << endl;
    }
    
    
    
    
    
    return 0;
}

运行截图

Snipaste_2020-05-23_20-41-10.png

Last modification:June 9th, 2020 at 10:51 pm
如果觉得我的文章对你有用,请随意赞赏