• 动态顺序表实现栈:顺序栈


    一、顺序栈的结构定义

    1. //顺序栈的结构定义
    2. typedef int STDataType;
    3. typedef struct Stack {
    4. STDataType* a;
    5. int top;
    6. int capacity;
    7. }ST;

    二、顺序栈的初始化

    1. //顺序栈的初始化
    2. void STInit(ST* pst)
    3. {
    4. assert(pst);
    5. pst->a = NULL;
    6. pst->top = 0;//top指针指向栈顶元素的下一位
    7. pst->capacity = 0;//顺序栈的容量
    8. }

    三、顺序栈的打印

    1. //顺序栈的打印
    2. void STPrint(ST pst)
    3. {
    4. for (int i = 0; i < pst.top; i++)
    5. {
    6. printf("%d ", pst.a[i]);
    7. }
    8. printf("\n");
    9. }

    四、顺序栈的入栈

    1. //顺序栈的入栈
    2. void STPush(ST* pst, STDataType x)
    3. {
    4. assert(pst);
    5. //检查扩容
    6. if (pst->top == pst->capacity)
    7. {
    8. int newcapacity = pst->capacity == 0 ? 4 : 2 * pst->capacity;
    9. STDataType* p = (STDataType*)realloc(pst->a, newcapacity * sizeof(STDataType));
    10. if (p == NULL)
    11. {
    12. perror("realloc fail");
    13. exit(-1);
    14. }
    15. else
    16. {
    17. pst->a = p;
    18. pst->capacity = newcapacity;
    19. }
    20. }
    21. pst->a[pst->top++] = x;
    22. }

    五、顺序栈的出栈

    1. //顺序栈出栈
    2. void STPop(ST* pst)
    3. {
    4. assert(pst);
    5. assert(pst->top > 0);
    6. pst->top--;
    7. }

    六、求顺序栈栈顶元素

    1. //求顺序栈栈顶元素
    2. STDataType STTop(ST* pst)
    3. {
    4. assert(pst);
    5. assert(pst->top > 0);
    6. return pst->a[pst->top - 1];
    7. }

    七、顺序栈判空

    1. //顺序栈判空
    2. bool STEmpty(ST* pst)
    3. {
    4. assert(pst);
    5. return pst->top == 0;
    6. }

    八、顺序栈销毁

    1. //顺序栈销毁
    2. void STDestroy(ST* pst)
    3. {
    4. assert(pst);
    5. if (pst->a != NULL)
    6. {
    7. free(pst->a);
    8. pst->a = NULL;
    9. pst->top = 0;
    10. pst->capacity = 0;
    11. }
    12. }

    九、测试代码

    1. void test01()
    2. {
    3. //定义顺序栈
    4. ST st;
    5. //初始化顺序栈
    6. STInit(&st);
    7. //顺序栈入栈
    8. STPush(&st, 1);
    9. STPush(&st, 2);
    10. STPush(&st, 3);
    11. STPush(&st, 4);
    12. STPush(&st, 5);
    13. //顺序栈打印
    14. STPrint(st);
    15. //顺序栈出栈
    16. STPop(&st);
    17. STPop(&st);
    18. STPop(&st);
    19. //顺序栈打印
    20. STPrint(st);
    21. //打印栈顶元素
    22. printf("%d\n", STTop(&st));
    23. //顺序栈判空
    24. if (STEmpty(&st))
    25. printf("空\n");
    26. else
    27. printf("非空\n");
    28. //顺序栈出栈
    29. STPop(&st);
    30. STPop(&st);
    31. //顺序栈判空
    32. if (STEmpty(&st))
    33. printf("空\n");
    34. else
    35. printf("非空\n");
    36. //顺序栈销毁
    37. STDestroy(&st);
    38. }
    39. int main()
    40. {
    41. test01();
    42. return 0;
    43. }
  • 相关阅读:
    热成像夜视仪和夜视仪的优缺点
    机器学习强基计划1-1:图文详解感知机算法原理+Python实现
    服务器配置怎么查看
    12.Babel
    降维算法实战项目(1)—使用PCA对二维数据降维(Python代码+数据集)
    多线程与并发 - 常见的几种锁的实现方式
    Docker的数据卷
    宁波银行金融科技部2023届校招开始了!内推码:90OF50
    Python 专栏目录索引
    MySQL视图&用户管理
  • 原文地址:https://blog.csdn.net/2301_76197086/article/details/134538206