顺序栈实现十进制与二进制的转化

用顺序栈实现十进制与二进制的转化

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

 

posted @ 2019-04-23 11:19  孙贤超  阅读(4819)  评论(0编辑  收藏  举报