【数据结构】顺序栈操作集

Code

/*
InitStack(&S):初始化一个空栈S。
StackEmpty(S):判断一个栈是否为空,若栈为空则返回true,否则返回false。
Push(&S, x):进栈,若栈S未满,则将x加入使之成为新栈顶。
Pop(&S, &x):出栈,若栈非空,则弹出栈顶元素,并用x返回。
GetTop(S, &x):读栈顶元素,若栈非空则用x返回栈顶元素。
ClearStack(&S):销毁栈,并释放S占用的内存空间。
 * */
#include <iostream>
using namespace std;
#define MaxSize 50
#define ElemType int
typedef struct {
    ElemType data[MaxSize]={0};
    int top;//栈顶“指针” 就指向栈顶元素,不是栈顶元素的下一位空白区域
}SqStack;
/*
 从下标为0开始存储
 栈空条件:S.top == -1
 栈长:S.top+1
 栈满条件:S.top == MaxSize-1
 * */
//初始化
void InitStack(SqStack &S){
    //要做的工作就是将栈空;
    S.top=-1;
}
//判断栈空
bool StackEmpty(SqStack S){
    if(S.top == -1)
        return true;
    else
        return false;
}
//进栈
bool Push(SqStack &S,ElemType x){
    if(S.top==MaxSize-1)//如果栈满,返回false
        return false;
    S.data[++S.top]=x;
    return true;
}
//出栈
bool Pop(SqStack &S, ElemType x){
    if(S.top==-1)//栈空,无法出
        return false;
    x=S.data[S.top];
    S.top--;
    return true;
}
//打印
void show(SqStack S){
    for(int i=0;i<=S.top;i++){
        cout<<S.data[i]<<" ";
    }
}
//读取栈顶元素,用x接受
ElemType GetTop(SqStack S, ElemType &x){
    if(S.top==-1)
        return -1;
    x=S.data[S.top];
    return x;
}
//销毁栈,并释放S占用的内存空间
void ClearStack(SqStack &S){
    //顺序栈不用释放空间。
}
int main(){
    SqStack S;
    InitStack(S);
    cout<<S.top<<endl;
    Push(S,3);
    Push(S,6);
    Push(S,11);
    show(S);
    return 0;
}

Input && Output

-1
3 6 11
Process finished with exit code 0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值