完整的代码,请看下面的源代码:#include<stdio.h>
#include<stdlib.h>
#include<math.h> /*pow()函数调用时用到的库函数*/
#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)//入栈
{
if ( s->top - s->base == s->stackSize)//栈的检查 /*判断语句*/
{
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);
printf("请输入一个二进制的数,回车结束单前输入:%d\n", len); /*格式化输出*/
scanf("%c", &c); /*格式化输入*/
while (c != ' ')
{
push(&s, c);
scanf("%c", &c); /*格式化输入*/
}
getchar();
len = StackLen(s);
printf("栈的当前容量是:%d\n", len);
for(i = 0; i < len; i++)
{
pop(&s, &c);
sum = sum + (c - 48)*pow(2,3); /*pow(x,y), 注:x,y必须要是常量,否则会报错*/
}
printf("转换为十进制数是:%d\n", len);
return 0;
}
|