顺序栈及其实现

lixiangrong
2024-01-05 / 0 评论 / 12 阅读 / 正在检测是否收录...
#include <stdio.h>
#include <stdlib.h>

typedef int dataType;
#define MAX_SIZE 100

// 2.3 顺序栈(设定top=0为空栈)
typedef struct
{
    dataType a[MAX_SIZE];
    int top;
}seqStack;

// 1.初始化(置空)栈
void init(seqStack *st)
{
    st->top = 0;
}

// 2.判断栈是否为空
int empty(seqStack st)
{
    return st.top ? 0:1;
}

// 3.读栈顶元素
dataType read(seqStack st)
{
    if(empty(st))
    {
        printf("栈是空的!\n");
        exit(1);
    }
    return st.a[st.top-1];
}

// 4.元素x进栈
void push(seqStack *st, dataType x)
{
    if(st->top == MAX_SIZE)
    {
        printf("栈已满,无法进栈!\n");
        exit(1);
    }
    st->a[st->top] = x;
    st->top+=1; // 或st->top++;
}

// 5.出栈
void pop(seqStack *st)
{
    if(!st->top)
    {
        printf("栈已空,无法出栈!");
        exit(1);
    }
    st->top-=1; // 或st->top--;
}

int main()
{
    seqStack st; // 定义栈
    init(&st); // 初始化栈
    dataType x = 1;
    push(&st,x); // 数据元素x进栈
    printf("%d\n", read(st)); // 读栈顶元素
    pop(&st); // 出栈
    pop(&st); // 出栈
    return 0;
}
0

评论 (0)

取消