|
发表于 2017-9-26 16:38:00
|
显示全部楼层
完整的代码,请看下面的源代码:
- #include<stdio.h>
- #include<stdlib.h>
- [color=Red]#include<math.h> /*pow()函数调用时用到的库函数*/[/color]
- #define STACK_INIT_SIZE 20
- #define STACRINCREMENT 10
- typedef char ElemType;
- typedef struct
- {
- ElemType *base;//栈顶
- ElemType *top;//栈底
- int stackSize;
- }sqStack;
- void InitStack(sqStack *s)//初始化栈
- {
- s->base = (ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
- if (!s->base)
- {
- exit(0);
- }
- s->top = s->base;
- s->stackSize = STACK_INIT_SIZE;
- }
- void push(sqStack *s, ElemType e)//入栈
- {
- [color=Red]if ( s->top - s->base == s->stackSize)//栈的检查 /*判断语句*/[/color]
- {
- s->base = (ElemType*)realloc(s->base, (s->stackSize + STACRINCREMENT) * sizeof(ElemType));
- if (!s->base)
- {
- exit(0);
- }
- }
- *(s->top) = e;
- s->top++;
- }
- void pop(sqStack *s, ElemType *e)
- {
- if (s->top == s->base)
- {
- return;
- }
- *e= *--(s->top);
- }
- int StackLen(sqStack s)
- {
- return(s.top - s.base);
- }
- int main()
- {
- ElemType c;
- sqStack s;
- int len, i, sum = 0;
- InitStack(&s);
- [color=Red]printf("请输入一个二进制的数,回车结束单前输入:%d\n", len); /*格式化输出*/[/color]
- [color=Red]scanf("%c", &c); /*格式化输入*/[/color]
- while (c != ' ')
- {
- push(&s, c);
- [color=Red] scanf("%c", &c); /*格式化输入*/[/color]
- }
- getchar();
- len = StackLen(s);
- printf("栈的当前容量是:%d\n", len);
- for(i = 0; i < len; i++)
- {
- pop(&s, &c);
- sum = sum + (c - 48)*pow[color=Red](2,3); /*pow(x,y), 注:x,y必须要是常量,否则会报错*/[/color]
- }
- printf("转换为十进制数是:%d\n", len);
- return 0;
- }
复制代码 |
|