栈--数据结构

初始化栈、入栈、出栈

栈:只允许在一端进行插入或删除操作的线性表 栈顶(Top)

代码实战步骤依次是初始化栈,判断栈是否为空,压栈,获取栈顶元素,弹栈。

代码

#include 

#define MaxSize 50
typedef int ElemType;
typedef struct {
    ElemType data[MaxSize];//数组
    int top;//始终指向栈顶的一个变量
}SqStack;

//初始化栈
void InitStack(SqStack &S){
    S.top = -1;//代表栈为空,就是S.top = -1,让栈为空
}

bool StackEmpty(SqStack S){
    if(-1 == S.top){
        return true;
    }else{
        return false;
    }
}

//入栈
bool Push(SqStack &S,ElemType x){
//    判断是否满了
    if(S.top == MaxSize - 1){
        return false;
    }
    S.data[++S.top] = x;//等价于S.top = S.top + 1;       S.data[S.top] = x;
     return true;
}

//获取栈顶元素
bool GetTop(SqStack S,ElemType &m){
    if(StackEmpty(S)){
        return false;
    }
    m = S.data[S.top];//拿栈顶元素
    return true;
}

//弹栈
bool Pop(SqStack &S,ElemType &m){
    if(StackEmpty(S)){
        return false;
    }
    m = S.data[S.top--];//出栈
    return true;
}

int main(){
    SqStack S;
    InitStack(S);
    bool flag;
    flag = StackEmpty(S);
    if(flag){
        printf("stack is empty\n");
    }
    Push(S,3);
    Push(S,4);
    Push(S,5);
    ElemType m;
    flag = GetTop(S,m);
    if(flag){
        printf("get top %d\n",m);
    }
    flag = Pop(S,m);
    if(flag){
        printf("pop element %d\n",m);
    }
    return 0;
}

结果

栈--数据结构_第1张图片

你可能感兴趣的:(数据结构,数据结构,c语言,开发语言)