#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define STACK_INIT_SIZE 20
#define STACKINCREMENT 10
typedef char ElemType; // input by char
typedef struct
{
ElemType *base;
ElemType *top;
int stackSize;
}sqStack;
// 函数功能:初始化栈
// 参数*s:栈的地址
void InitStack(sqStack *s) //初始化栈的过程 *s 传一个地址进来,一处改变处处改变
{
s -> base = (ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
if(!s->base) //分配失败
{
exit(0);
}
s->top = s->base;
s->stackSize = STACK_INIT_SIZE;
}
// 函数功能:入栈操作
// 参数*s:栈的地址
// 参数e:待压入栈的元素
void Push(sqStack *s , ElemType e)
{
//压栈存在的问题:当栈满,在压入时,就会出现溢出 所以要先判断栈是否满
if(s->top - s->base >= s->stackSize) //判断栈满
{
s->base = (ElemType *)realloc(s->base, (s->stackSize + STACKINCREMENT* sizeof(ElemType))); //动态增加内存
if(!s->base)
{
exit(0);
}
}
*(s->top) = e;
s->top ++;
}
// 函数功能:弹栈操作
// 参数*s:栈的地址
// 参数e:存放从栈里弹出的数据
void Pop(sqStack *s , ElemType *e)//出栈
{
if(s->top == s->base) //先判断栈内是否有值
{
return;
}
*e = *--(s->top);
}
// 函数功能:计算栈s的当前长度
// 参数s:栈
int StackLen(sqStack s) //求栈的当前容量 只要将栈的结构传过来就可以 不对栈做任何修改,所以不用传指针
{
return (s.top - s.base);//指针相减,事实上不是将同类型的地址相减,而是得到两个指针所指向地之间相差的这个类型元素的个数,如果是高地址减低地址就是正数,否则就是负数
} //如果传进来的 是指针,则用 -> 取其成员 如果传进来的是结构,则用.取 (归属于)
int main()
{
ElemType c;
sqStack s;
int len , i ,sum = 0;
InitStack(&s); //初始化栈
printf("请输入二进制数,以#结束!\n");
scanf("%c",&c); //按字符的方式输入 键盘缓冲区
while ( c != '#')
{
Push(&s ,c);
scanf("%c", &c);
}
getchar();//把'\n'从缓冲区去掉
len = StackLen(s);
printf("栈的当前容量是:%d\n",len);
for(i = 0; i < len; i++)
{
Pop(&s, &c);
printf("i是:%d\n",i);
printf("c是:%d\n",c);
sum = sum + (c-48) * pow(2 , i);
printf("sum是:%d\n",sum);
}
printf("转换为十进制数是:%d\n", sum);
return 0;
}