• 数据结构day7栈-链式栈原理及实现


     

     

     全部代码:

    main.c

    1. #include
    2. #include
    3. #include
    4. #include "linkstack.h"
    5. int main(int argc, char *argv[])
    6. {
    7. linkstack s;
    8. s = stack_create();
    9. if(s == NULL)
    10. {
    11. return -1;
    12. }
    13. stack_push(s, 10);
    14. stack_push(s, 20);
    15. stack_push(s, 30);
    16. stack_push(s, 40);
    17. stack_push(s, 50);
    18. #if 0
    19. while(!stack_empty(s))//栈不空,出栈
    20. {
    21. printf("pop : %d\n",stack_pop(s));
    22. }
    23. #endif
    24. s = stack_free(s);
    25. return 0;
    26. }

    linkstack.h

    1. typedef int data_t;
    2. typedef struct node{
    3. data_t data;
    4. struct node *next;
    5. }listnode, *linkstack;
    6. linkstack stack_create();
    7. int stack_push(linkstack s, data_t value);
    8. data_t stack_pop(linkstack s);
    9. int stack_empty(linkstack s);
    10. data_t stack_top(linkstack s);
    11. linkstack stack_free(linkstack s);

    linkstack.c

    1. #include
    2. #include
    3. #include
    4. #include "linkstack.h"
    5. linkstack stack_create(){
    6. linkstack s;
    7. s = (linkstack)malloc(sizeof(listnode));
    8. if(s == NULL)
    9. {
    10. printf("malloc failed\n");
    11. return NULL;
    12. }
    13. s->data = 0;
    14. s->next = NULL;
    15. }
    16. int stack_push(linkstack s, data_t value){
    17. linkstack p;
    18. if(s == NULL)
    19. {
    20. printf("s is NULL\n");
    21. return -1;
    22. }
    23. p = (linkstack)malloc(sizeof(listnode));
    24. if(p == NULL)
    25. {
    26. printf("malloc failed\n");
    27. return -1;
    28. }
    29. p->data = value;
    30. //p->next = NULL;
    31. p->next = s->next;
    32. s->next = p;
    33. return 0;
    34. }
    35. data_t stack_pop(linkstack s){
    36. linkstack p;
    37. data_t t;
    38. p = s->next;
    39. s->next = p->next;
    40. t = p->data;
    41. free(p);
    42. p=NULL;
    43. return t;
    44. }
    45. //1-empty
    46. int stack_empty(linkstack s){
    47. if(s == NULL)
    48. {
    49. printf("s is NULL\n");
    50. return -1;
    51. }
    52. return (s->next == NULL ? 1 : 0);
    53. }
    54. data_t stack_top(linkstack s){
    55. return (s->next->data);//栈顶的元素
    56. }
    57. linkstack stack_free(linkstack s){
    58. linkstack p;
    59. if(s == NULL)
    60. {
    61. printf("s is NULL\n");
    62. return NULL;
    63. }
    64. while(s != NULL)
    65. {
    66. p = s;
    67. s = s->next;
    68. printf("free:%d\n",p->data);
    69. free(p);
    70. }
    71. return NULL;
    72. }

     运行结果:

  • 相关阅读:
    2022-10-20 C++并发编程( 三十五 )
    15、Mybatis获取参数值的情况1(mapper接口方法的参数为单个字面量类型)
    论文笔记: 图神经网络 GAT
    java反射机制详解
    VC界面库Xtreme Toolkit Pro全新发布v22.1——支持VS 2022主题
    Go语言~反射
    vue+DataV 易懂使用方式
    10 创建型模式-原型模式
    某网站cookies携带https_ydclearance获取正文
    外包干了2个月,技术退步明显...
  • 原文地址:https://blog.csdn.net/AuroraSmith/article/details/132700753