1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<math.h> 4 5 #define STACK_INIT_SIZE 20 6 #define STACKINCREMENT 10 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*sizeof(ElemType)); 19 if(!s->base) 20 { 21 exit(0); 22 } 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 exit(0); 35 } 36 37 *(s->top) = e; 38 s->top++; 39 } 40 41 42 void Pop(sqStack *s , ElemType* e) 43 { 44 if(s->top == s->base) 45 { 46 return; 47 } 48 *e = *(--s->top ); 49 } 50 51 int StackLen(sqStack s) 52 { 53 return (s.top - s.base); 54 } 55 56 void main() 57 { 58 ElemType e; 59 sqStack s; 60 int len,i,sum = 0; 61 62 InitStack(&s); 63 64 printf("请输入2进制数,输入#表示结束:"); 65 scanf("%c",&e);//以字符形式输入1111001,会一个一个字符的形式输入到缓冲区,要以整形,则1111001一次以整形数存放在栈中占一个空间 66 while(e != '#') 67 { 68 Push(&s,e); 69 scanf("%c",&e); 70 } 71 getchar();//把' '从缓冲区中去掉 72 73 len = StackLen(s); 74 75 printf("栈当前容量是:%d ",len); 76 for(i = 0 ; i <len ;i++) 77 { 78 Pop(&s,&e); 79 sum = sum + (e - 48)*pow(2,i);///*************** 80 81 } 82 printf("转换为十进制数为:%d ",sum); 83 }