妙趣横生的算法实例1-4

#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]); 
    }  

就可以了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值