MagicDevil

Menu

StaticStack 静态栈C语言算法(数组栈)

静态栈

通过数组形式表示的静态栈,代码量和复杂程度都比较低,且在读取时可以快速访问,但是栈的空间大小固定,当处理不确定数据量的运算时容易出现栈满情况。

因此静态栈的方法普遍适用于数据量确定或范围大致确定的运算,例如可以运用于汉罗塔游戏运算、算数优先级运算程序等。

 

实现功能

初始化栈

入栈

出栈

清空栈

取栈的大小

打印栈的内容

 

代码

GitHub:https://github.com/MagicDevilZhang/myDataStructProject/blob/master/StaticStack.cpp

CSDN:https://blog.csdn.net/MagicDevilZhang/article/details/84256202

以下代码纯手工编写,欢迎指出错误和优化方法。

  1. #include <stdio.h>
  2. #include <windows.h>
  3. #define SUCCESS 1
  4. #define ERROR -1
  5. #define ElemType int
  6. #define StatusType int
  7. #define MAX 100
  8. typedef struct StackNode
  9. {
  10. ElemType data[MAX];
  11. int top;
  12. } StackNode, *Stack;
  13. //1.初始化栈空间
  14. StatusType InitStack(Stack &S)
  15. {
  16. S = (Stack)malloc(sizeof(StackNode));
  17. S->top = -1;
  18. return SUCCESS;
  19. }
  20. //2.入栈
  21. StatusType PushStack(Stack &S, ElemType content)
  22. {
  23. if (S->top< MAX -1&& content != ERROR)
  24. { //当栈未满
  25. S->data[++S->top] = content;
  26. return SUCCESS;
  27. }
  28. return ERROR;
  29. }
  30. //3.出栈
  31. ElemType PopStack(Stack &S)
  32. {
  33. if (S->top!=-1)
  34. {
  35. return (S->data[S->top--]);
  36. }
  37. return ERROR;
  38. }
  39. //4.清空栈
  40. StatusType ClearStack(Stack &S)
  41. {
  42. S->top = -1;
  43. }
  44. //5.取栈的大小
  45. int getStackNum(Stack &S)
  46. {
  47. return S->top+1;
  48. }
  49. //6.打印栈的内容
  50. StatusType PrintStack(Stack &S)
  51. {
  52. intgetStackNum(Stack & S);
  53. printf("Stack Information\n");
  54. for (int i =0; i <= S->top; i++)
  55. {
  56. printf(" |- Stack %d : %d\n", i, S->data[i]);
  57. }
  58. printf("Num : %d\n", getStackNum(S));
  59. return SUCCESS;
  60. }
  61. int main(int argc, char const *argv[])
  62. {
  63. Stack stack, q;
  64. InitStack(stack);
  65. InitStack(q);
  66. PushStack(stack, 1);
  67. PushStack(stack, 3);
  68. PushStack(stack, 5);
  69. PushStack(stack, 7);
  70. PrintStack(stack);
  71. PushStack(q, PopStack(stack));
  72. PushStack(q, PopStack(stack));
  73. PushStack(q, PopStack(stack));
  74. PushStack(q, PopStack(stack));
  75. PushStack(q, PopStack(stack));
  76. PrintStack(q);
  77. printf("%d\n", getStackNum(stack));
  78. system("pause");
  79. return0;
  80. }
共写了1542个字