c语言将2进制数转化为10进制数(栈的初始化,进栈,出栈)

 1 //c语言描述  将2进制转化为10进制
 2 #include <stdio.h>
 3 #include <stdlib.h>
 4 #include <math.h>
 5 #define STACK_INIT_SIZE 20
 6 #define     //栈满后再分配
 7 
 8 typedef char ElemType;
 9 typedef struct
10 {
11     ElemType *base;   //栈底
12     ElemType *top;     //栈底
13     int stackSize;      // 栈的容量
14 }sqStack;
15 
16 void InitStack (sqStack *s)    //初始化栈
17 {
18        s -> base = (ElemType*) malloc(STACK_INIT_SIZE);
19        if(! s-> base)
20        { 
21            printf("分配空间失败");
22            exit(0);
23        }
24       s->top=s->base ;
25       s->stackSize = STACK_INIT_SIZE;
26 }
27 
28 void Push (sqStack *s, ElemType e)   //进栈
29 {
30        if(s->top - s->base >= s->stackSize)
31        {
32              s->base =(ElemType*) realloc(s->base,(s->stackSize + STACKINCREMENT) * sizeof(ElemType));//分配空间
33                     if(! s-> base)
34                    { 
35                      printf("分配空间失败");
36                      exit(0);
37                    }
38        }
39        *(s->top) = e;           //先赋值
40        s->top++;               //指针在+1
41 }
42 
43 void Pop(sqStack * s,ElemType *e)    //出栈
44 {
45     if(s->top == s->base )
46     {
47        printf("栈为空,没法出栈");
48            return;
49     }
50     *e = *--(s->top);    //首先把s->top的元素赋值给e 再将地址--
51 }
52 
53      
54 int StackLen (sqStack s)    //返回栈有多少个元素
55 {
56    return ( s.top - s.base);  //  实质是地址相减 除以ElemType 
57 } 
58 
59 
60 int main()
61 {
62     ElemType c;  //声明一个字符c
63     sqStack s;   //声明一个结构体s
64 
65     int len,i,sum=0;  
66     InitStack(&s);     //初始化栈
67     printf("请输入二进制数,输入#结束!\n");
68     scanf("%c",&c);
69     while( c != '#')
70     {
71        Push (&s,c);
72        scanf ("%c",&c);
73     }
74      getchar();   //接收回车键
75      len =StackLen(s);
76      printf("栈的当容量:%d\n",len);
77      for(i=0; i<len ; i++)
78      {
79         Pop(&s,&c);
80          sum = sum + (c-48) * pow(2,i);
81      }
82      printf("转化为十进制数为:%d \n",sum);
83 
84      return 0;
85 }

 

posted @ 2016-04-18 00:18  MrPat  阅读(2812)  评论(0编辑  收藏  举报