栈结构
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <math.h> 4 #include <windows.h> 5 #define STACK_INIT_SIZE 20 6 #define STACKINCREMENT 10 7 8 typedef char ElemType; 9 typedef struct 10 { 11 ElemType *top; 12 ElemType *base; 13 int stacksize; 14 }sqStack; 15 16 //创建一个栈 17 void InitStack(sqStack *s) 18 { 19 s->base = (ElemType*)malloc(STACK_INIT_SIZE * sizeof(ElemType)); //内存中开辟一段连续空间作为栈空间 20 if(!s->base) printf("Init Error"); //失败检测 21 s->top = s->base; //一开始栈顶就是栈底 22 s->stacksize = STACK_INIT_SIZE; //设置最大容量 23 } 24 25 //入栈操作 26 void Push(sqStack *s,ElemType e) 27 { 28 if(s->top - s->base >= s->stacksize) //栈满追加空间 29 { 30 //realloc函数改变指针指向的内存大小,而且原始内存中的数据保持不变,新的内存一定要大于以前的 31 s->base = (ElemType*)realloc(s->base,(s->stacksize + STACKINCREMENT)*sizeof(ElemType)); 32 if(!s->base) printf("Push Error"); //分配内存失败 33 s->top = s->base + s->stacksize; //重新定位栈顶指针 34 s->stacksize = s->stacksize + STACKINCREMENT; //设置最大容量 35 } 36 *(s->top) = e; //放入数据 37 s->top++; //栈顶指针上移 38 } 39 40 //出栈操作 41 void Pop(sqStack *s,ElemType *e) 42 { 43 if(s->top == s->base) return; //栈空 44 *e = *--(s->top); //下移栈顶指针取出数据 45 } 46 47 //清空一个栈 48 void ClearStack(sqStack *s) 49 { 50 s->top = s->base; //把栈顶指针指向栈底 51 } 52 53 //销毁一个栈 54 void DestroyStack(sqStack *s) 55 { 56 int i,len; 57 len = s->stacksize; 58 for(i=0;i<len;i++) 59 { 60 free(s->base); 61 s->base++; 62 } 63 s->base = s->top = NULL; 64 s->stacksize = 0; 65 } 66 67 //计算当前栈的容量 68 int StackLen(sqStack s) 69 { 70 return (s.top - s.base); 71 } 72 73 int main() 74 { 75 ElemType c; 76 sqStack s; 77 int len,i,sum=0; 78 printf("Please input a Binary digit\n"); 79 InitStack(&s); //创建一个栈,用来存放二进制字符串 80 81 //输入二进制数 82 scanf("%c",&c); 83 while(c!='#') //回车的键值 84 { 85 Push(&s,c); 86 scanf("%c",&c); 87 } 88 fflush(stdin); 89 getchar(); 90 len = StackLen(s); //得到栈中元素个数 91 for(i=0;i<len;i++) 92 { 93 Pop(&s,&c); 94 sum = sum+(c-48)*pow(2,i); //转换为十进制 95 } 96 printf("Decimal is %d\n",sum); 97 system("pause"); 98 return 0; 99 }
——现在的努力是为了小时候吹过的牛B!!