顺序栈的基本操作实现

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#define MAXLIE 100
typedef int DataType;
typedef struct {                //顺序栈存储类型
    DataType data[MAXLIE];     //存放顺序栈的数组
    int top;                  //栈顶元素的位置
}SqStack;
void InitStack(SqStack* S) {
    S->top = -1;           //初始化栈顶指针为空
}
int EmptyStack(SqStack *S) {
    if (S->top == -1)     //判断栈是否为空
        return 1;
    else
        return 0;
}
int FullStack(SqStack* S) {
    if (S->top == MAXLIE - 1)  //栈是否满
        return 1;
    else
        return 0;
}
int Push(SqStack* S, DataType x) {
    if (FullStack(S)) {       //调用FullStack(S)函数,判断栈是否满
        printf("栈已满,不能进!");
        return 0;
    }
    else {
        S->top++;
        S->data[S->top] = x;
        return 1;
    }
}
int Pop(SqStack *S, DataType *x) {
    if (EmptyStack(S)) {       //调用EmptyStack(S)函数,判断栈是否为空
        printf("栈为空,出不了!");
        return 0;
    }
    else {
        *x = S->data[S->top];
        S->top--;
        return 1;
    }
}
int GetStack(SqStack* S, DataType* x) {
    if (EmptyStack(S)) {       //调用EmptyStack(S)函数,判断栈是否为空
        printf("栈为空,取不了!");
        return 0;
    }
    else {
        *x = S->data[S->top];
        return 1;
    }
}
int main() {
    SqStack  S;
    DataType x;
    int i,n;
    InitStack(&S);//初始化栈
    EmptyStack(&S);//判断栈空
    FullStack(&S);//判断栈满
    printf("请输入要进栈的元素个数:");
    scanf("%d", &n);
    printf("请输入%d个整数:", n);
    for (i = 0; i < n; i++) {
        scanf("%d", &x);
        Push(&S, x);//进栈
    }    
    printf("请输入要出栈的元素个数:");
    scanf("%d", &n);
    printf("请输入出栈的元素:");
    for (i = 0; i < n; i++) {
        scanf("%d", &x);
        Pop(&S, &x);//出栈
    }    
    GetStack(&S, &x);//取栈顶元素
    printf("栈顶元素为:%d",x);
    return 0;
}

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值