【数据结构】栈的顺序存储结构(C语言版)

#include <stdio.h>
#include <stdlib.h>

// 初始长度
#define STACK_INIT_SIZE 10
// 扩容量
#define STACK_INCREMENT 100

typedef int ElemType;
// 栈的顺序存储结构
typedef struct {
    // 栈顶指针
    ElemType *top;
    // 栈底指针
    ElemType *base;
    // 栈长
    int stackSize;
} Stack;

// 创建栈
int initStack(Stack &S);
// 判断栈是否为空
int isEmpty(Stack &S);
// 栈扩容
int grow(Stack &S);
// 入栈
int push(Stack &S, ElemType e);
// 出栈
int pop(Stack &S);
// 求栈长
int length(Stack &S);
// 清空栈
int clear(Stack &S);

int initStack(Stack &S) {
    S.base = (ElemType *) malloc(STACK_INIT_SIZE * sizeof(ElemType));

    if (!S.base)return -1;

    S.top = S.base;
    S.stackSize = STACK_INIT_SIZE;

    return 0;
}

int isEmpty(Stack &S) {
    if (S.base == S.top) {
        printf("stack is empty");
        exit(-1);
    }

    return 0;
}

int grow(Stack &S) {
    if (S.top - S.base >= S.stackSize) {
        // 重新分配存储空间
        S.base = (ElemType *) realloc(S.base, (S.stackSize + STACK_INCREMENT) * sizeof(ElemType));
        if (!S.base)return -1;

        S.top = S.base + S.stackSize;
        S.stackSize += STACK_INCREMENT;
    }

    return 0;
}

int push(Stack &S, ElemType e) {
    grow(S);
    // e赋值给栈顶指针所指的空间,然后指针上移一位
    *S.top++ = e;

    return 0;
}

ElemType pop(Stack &S) {
    isEmpty(S);
    // 栈顶指针是指向最后一个入栈的元素的后一位
    return *--S.top;
}

int length(Stack &S) {
    int len = 0;
    ElemType *temp = S.top;

    while (temp != S.base) {
        len++;
        temp--;
    }

    return len;
}

int clear(Stack &S) {
    while (S.top != S.base) {
        *--S.top = NULL;
    }

    return 0;
}


int main() {

    Stack S;
    // 创建栈
    initStack(S);

    printf("When there is no element on the stack, the stack length is:%d\n", length(S));

    // 10个元素入栈
    for (int i = 0; i < 10; ++i) {
        push(S, i + 1);
    }

    printf("After 10 elements are put on the stack, the stack length is:%d\n", length(S));

    // 10个元素出栈
    for (int i = 0; i < 10; ++i) {
        printf("%d ", pop(S));
        if(i == 9)printf("\n");
    }

    printf("After 10 elements are popped out of the stack, the stack length is:%d\n", length(S));

    // 清空栈
    clear(S);
    printf("After clearing the stack, the stack length is:%d\n", length(S));

    push(S, 419);
    printf("%d\n", pop(S));

    return 0;
}

运行结果
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值