当前位置:   article > 正文

数据结构(3)(顺序栈)

数据结构(3)(顺序栈)

 栈:

      栈是限定仅在栈顶进行插入和删除操作的线性表,在操作的时候,只允许栈顶改变不允许栈底改变,具有后进先出的特征。

顺序栈:

      顺序栈是一种使用数组实现的栈,也称为数组栈。其基本思路是通过数组来存储栈中的元素,并通过栈顶指针指示栈顶元素在数组中的位置。

     也就是说,相当于只能对最后一个元素进行增,删,查的数组。

基本操作:

  1. #ifndef SEQSTACK_H
  2. #define SEQSTACK_H
  3. typedef struct{
  4. char name[32];
  5. char sex;
  6. int age;
  7. int score;
  8. }DATATYPE;
  9. typedef struct
  10. {
  11. DATATYPE* head;
  12. int tlen;
  13. int top;// clen
  14. }SeqStack;
  15. SeqStack*CreateSeqStack(int size); //创建
  16. int DestroySeqStack(SeqStack*ss); //销毁
  17. int PushSeqStack(SeqStack*ss,DATATYPE*data); //入栈
  18. int PopSeqStack(SeqStack*ss); //出栈
  19. int IsEmptySeqStack(SeqStack*ss); //判断栈是否为空
  20. int IsFullSeqStack(SeqStack*ss); //判断栈是否为满
  21. int GetSizeSeqStack(SeqStack*ss); //获取栈当前大小
  22. DATATYPE*GetTopSeqStack(SeqStack*ss); //获取栈顶元素
  23. #endif // SEQSTACK_H

实现:

  1. #include "seqstack.h"
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <stdio.h>
  5. SeqStack *CreateSeqStack(int size)
  6. {
  7. SeqStack* ss = ( SeqStack*)malloc(sizeof(SeqStack));
  8. if(NULL ==ss)
  9. {
  10. perror("CreateSeqStack error malloc1");
  11. return NULL;
  12. }
  13. ss->head = ( DATATYPE*)malloc(sizeof(DATATYPE)*size);
  14. if(NULL ==ss->head)
  15. {
  16. perror("CreateSeqStack error malloc2");
  17. return NULL;
  18. }
  19. ss->tlen = size;
  20. ss->top = 0;
  21. return ss;
  22. }
  23. int PushSeqStack(SeqStack *ss, DATATYPE *data)
  24. {
  25. if(NULL == ss ||NULL ==data)
  26. {
  27. fprintf(stderr,"SeqStack or data is null \n");
  28. return 1;
  29. }
  30. if(IsFullSeqStack(ss))
  31. {
  32. fprintf(stderr,"PushSeqStack full\n");
  33. return 1;
  34. }
  35. memcpy(&ss->head[ss->top],data,sizeof(DATATYPE));
  36. ss->top++;
  37. return 0;
  38. }
  39. int PopSeqStack(SeqStack *ss)
  40. {
  41. if(NULL == ss )
  42. {
  43. fprintf(stderr,"SeqStack is null \n");
  44. return 1;
  45. }
  46. if(IsEmptySeqStack(ss))
  47. {
  48. fprintf(stderr,"PopSeqStack is empty \n");
  49. return 1;
  50. }
  51. ss->top--;
  52. return 0;
  53. }
  54. int IsEmptySeqStack(SeqStack *ss)
  55. {
  56. return 0 == ss->top;
  57. }
  58. int IsFullSeqStack(SeqStack *ss)
  59. {
  60. return ss->top == ss->tlen;
  61. }
  62. DATATYPE *GetTopSeqStack(SeqStack *ss)
  63. {
  64. if(IsEmptySeqStack(ss))
  65. {
  66. return NULL;
  67. }
  68. return &ss->head[ss->top-1];
  69. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小舞很执着/article/detail/901155
推荐阅读
相关标签
  

闽ICP备14008679号