用顺序栈实现十进制转二进制(c语言)

怼烎@ 2022-05-09 14:33 252阅读 0赞
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #define M 100
  4. typedef int ElemType;
  5. typedef struct
  6. {
  7. ElemType data[M];
  8. int top;
  9. }Stack;
  10. //初始化栈
  11. void InitStack(Stack *s)
  12. {
  13. s->top = -1;
  14. }
  15. int Push(Stack *s,ElemType e)
  16. {
  17. if (s->top == M-1)
  18. {
  19. printf("栈满\n");
  20. return 0;
  21. }
  22. s->top++;
  23. s->data[s->top]=e;
  24. return 1;
  25. }
  26. //判断是否为空
  27. int Empty(Stack *s)
  28. {
  29. return(s->top==-1);
  30. }
  31. //出栈
  32. int Pop(Stack *s,ElemType *e)
  33. {
  34. if(Empty(s))
  35. {
  36. printf("\n Stack is free");
  37. return 0;
  38. }
  39. *e=s->data[s->top];
  40. s->top--;
  41. return 1;
  42. }
  43. void Conversion(int N)
  44. {
  45. int e;
  46. Stack *s = (Stack *)malloc(sizeof(Stack));
  47. InitStack(s);
  48. while(N)
  49. {
  50. Push(s,N%2);
  51. N=N/2;
  52. }
  53. while(!Empty(s))
  54. {
  55. Pop(s,&e);
  56. printf("%d",e);
  57. }
  58. }
  59. int main()
  60. {
  61. int n,m;
  62. while(1)
  63. {
  64. printf("1:进行转换,2:退出\n");
  65. scanf("%d",&n);
  66. switch(n)
  67. {
  68. case 1: printf("请输入待转换的整数值: ");
  69. scanf("%d",&m);
  70. printf("转换为二进制值为: ");
  71. Conversion(m);
  72. printf("\n");
  73. break;
  74. case 2: exit(0);
  75. default: printf("error\n");
  76. }
  77. }
  78. }

发表评论

表情:
评论列表 (有 0 条评论,252人围观)

还没有评论,来说两句吧...

相关阅读