经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » C 语言 » 查看文章
详解C语言数据结构之栈
来源:jb51  时间:2022/1/3 16:47:25  对本文有异议

栈的链式实现

主要内容

(1) 栈包含7个元素,依次是67,3,88,6,1,7,0,采用尾插入法创建 栈,为该栈设置两个指针,一个bottom和一个top指针;

(2) 入栈函数push,该函数完成向栈中插入元素的功能,利用push函数,将数字-9插入到栈内,并将栈里的元素遍历;

(3) 出栈函数pop,该函数完成从栈中删除元素的功能,利用pop函数,删除此时栈里面的3个元素,并遍历栈;

(4) 函数length,求出此时栈内元素的个数。

代码实现:

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. struct node
  4. {
  5. int date;
  6. struct node *next;
  7. };
  8. struct stack
  9. {
  10. struct node *bottom;
  11. struct node *top;
  12. }s;
  13. struct stack *creat(struct stack *s); //创建栈
  14. void push(struct stack *s,int e); //入栈
  15. void print(struct stack *s); //打印输出
  16. void pop(struct stack *s); //出栈
  17. void length(struct stack *s); //输出栈的长度
  18. int main()
  19. {
  20. struct stack *s;
  21. int e;
  22. s=creat(s);
  23. push(s,67);
  24. push(s,3);
  25. push(s,88);
  26. push(s,6);
  27. push(s,1);
  28. push(s,7);
  29. push(s,0);
  30. printf("初始栈元素为:");
  31. print(s);
  32. printf("\n");
  33. printf("\n");
  34. push(s,-9);
  35. printf("插入元素后:");
  36. print(s);
  37. printf("\n");
  38. printf("\n");
  39. pop(s);
  40. pop(s);
  41. pop(s);
  42. printf("删除元素后:");
  43. print(s);
  44. printf("\n");
  45. printf("\n");
  46. length(s);
  47. return 0;
  48. }
  49. struct stack *creat(struct stack *s)
  50. {
  51. s=(struct stack *)malloc(sizeof(struct stack ));
  52. s->bottom=s->top=(struct node *)malloc(sizeof(struct node));
  53. s->top->next=NULL;
  54. s->bottom->next=NULL;
  55. return s;
  56. }
  57. void push(struct stack *s,int e)//进栈
  58. {
  59. struct node *p;
  60. p=(struct node *)malloc(sizeof(struct node));
  61. p->date=e;
  62. p->next=NULL;
  63. s->top->next=p;
  64. s->top=p;
  65. }
  66. void pop(struct stack *s)// 出栈
  67. {
  68. struct node *p,*q;
  69. p=s->bottom;
  70. while(p->next!=NULL)
  71. {
  72. q=p;
  73. p=p->next;
  74. }
  75. q->next=NULL;
  76. s->top=q;
  77. }
  78. void print(struct stack *s)//打印输出
  79. {
  80. struct node *p = s->bottom->next;
  81. while(p!=NULL)
  82. {
  83. printf("%4d",p->date);
  84. p=p->next;
  85. }
  86. }
  87.  
  88. void length(struct stack *s)//计算长度
  89. {
  90. struct node *p=s->bottom->next;
  91. int i=0;
  92. while(p!=NULL)
  93. {
  94. i++;
  95. p=p->next;
  96. }
  97. printf("此时栈的长度为:%4d",i);
  98. }

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注w3xue的更多内容! 

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号