#include <stdio.h>
#include <malloc.h>
#include <math.h>
#define STACK_INIT_SIZE 10
#define STACK_INCREMENT_SIZE 10
typedef char ElemType;
typedef struct
{
ElemType *base;
ElemType *top;
int stackSize;
}stack;
void initStack(stack *s)
{
s->base = (ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
if(!(s->base)) return;
s->top = s->base;
s->stackSize = STACK_INIT_SIZE;
}
void pushStack(stack *s, ElemType e)
{
if((s->top - s->base) >= s->stackSize)
{
s->base = (ElemType *)realloc(s->base, (s->stackSize + STACK_INCREMENT_SIZE) * sizeof(ElemType));
if(!(s->base)) return;
s->top = s->base + s->stackSize;
s->stackSize = s->stackSize + STACK_INCREMENT_SIZE;
}
*(s->top) = e;
(s->top)++;
}
void popStack(stack *s, ElemType *e)
{
if(s->base == s->top) return;
*e = *(--(s->top));
}
int stackLen(stack s)
{
return (s.top - s.base);
}
void destroyStack(stack *s)
{
free(s->base);
s->base = s->top = NULL;
s->stackSize = 0;
}
//void destroyStack(stack *s)
//{
// int i, len;
// len = s->stackSize;
// for(i = 0; i < len; i++)
// {
// free(s->base);
// s->base++;
// }
//
// s->base = s->top = NULL;
// s->stackSize = 0;
//}
int power(int n)
{
int i;
int product = 1;
for(i = 1; i <= n; i++)
{
product = product * 2;
}
return product;
}
void main()
{
stack binaryToDecimalStack;
int i, len, decimal = 0;
ElemType pushBinary, popBinary;
initStack(&binaryToDecimalStack);
printf("请输入二进制数,以“;”结束:\n");
scanf("%c", &pushBinary);
while(pushBinary != ';')
{
pushStack(&binaryToDecimalStack, pushBinary);
scanf("%c", &pushBinary);
}
len = stackLen(binaryToDecimalStack);
for(i = 0; i < len; i++)
{
popStack(&binaryToDecimalStack, &popBinary);
while(popBinary != '0' && popBinary != '1')
{
printf("不好意思,您输入的不是二进制数据!:\n");
return;
}
decimal = decimal + (popBinary - 48) * power(i);
}
for(i = 0; i < len; i++)
{
printf("%c", *(binaryToDecimalStack.base++));
}
printf("转换成的二进制为:%d\n", decimal);
//destroyStack(&binaryToDecimalStack);
}
这个程序销毁栈的时候,在windows会崩溃,我也不知道怎么回事?有谁能告诉我吗?回头到linux下试试。
我刚开始把类型定义为int型,但是没有办法判断什么时候结束,而且,如果输入字符的话,就会出错,看书上定义为char型,感觉不错,而且char型占一个字节,而int要占4个字节。
我知道哪里错了,
for(i = 0; i < len; i++)
{
printf("%c", *(binaryToDecimalStack.base++)); //这句base++,base已经指向其它地方了,原因是你Pop的时候stack size没有--
}
把这里改为:
for(i = 0; i < len; i++)
{
printf("%c", binaryToDecimalStack.base[i]);
}
就可以了。