《数据结构》严蔚敏 用栈实现进制转换

基本思想很简单
原数:N
N = (N div d) X d + N mod d
在这里插入图片描述

//Order Stack
//apply of stack --- conversion of number systems

#include<stdio.h>
#include<stdlib.h>

#define STACK_INIT_SIZE 100
#define STACKINCREMENT  10

#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0


typedef int SElemType;
typedef int Status;

typedef struct
{
	SElemType *base;
	SElemType *top;

	int stackesize;

}SqStack;

Status
InitStack(SqStack *S)
{
	(*S).base =(SElemType *)malloc(STACK_INIT_SIZE * sizeof(SqStack));
	//why first I used the (*S).top ???
	//the verfy I always forget... So my code always weak...
	if(!S->base)
		exit(ERROR);

	(*S).top = (*S).base; // If you don't understand it ,I think you should learn about the structure in C firstly.
	(*S).stackesize = STACK_INIT_SIZE;

	return OK;
}

Status StackEmpty(SqStack *S)
{
	if(S->top == S->base)
		return TRUE;
	else
		return FALSE;

	// or use ? : make things seems concise

}

// When Push,first add then change the point

Status
Push(SqStack *S,SElemType e)
{
	//lack of verfy
	if(S->top - S->base >= S->stackesize)
	{
		S->base = (SElemType*)realloc(S->base,
			(S->stackesize + STACK_INIT_SIZE)*sizeof(SElemType));
		if(!S->base)
			exit(ERROR);
		S->top = S->base + S->stackesize;
		S->stackesize += STACKINCREMENT;
	}
	

	// the first 
	*(*S).top = e;
	S->top ++;
	
	return OK;	

}

//when pop,first change point then pop element

Status
Pop(SqStack *S,SElemType *e)
{
	if(StackEmpty(S) == 0)
	{
		S->top --;
		//e = (*S).top ;
		//well must write like this,orthise can;t getthe return value
		*e = *(*S).top; 
		//it this ok ? How poped?
		return OK;
	}
	else
		return ERROR;

}

Status
conversion_change(SqStack S, int origin_number,int conversion)
{
	int result_number;
	while(origin_number)
	{
		Push(&S,origin_number % conversion);
		origin_number /= conversion;
	}

	printf("the result number is: ");

	while(!StackEmpty(&S))
	{
		Pop(&S,&result_number);
		printf("%d",result_number);
	}

	printf("\n");
	return OK;
}

int main(int argc, char const *argv[])
{
	int origin_number,conversion;

	SqStack S;
	InitStack(&S);

	printf("please enter the origin_number: ");
	scanf("%d",&origin_number);

	printf("please enter the conversion you want change :");
	scanf("%d",&conversion);

	conversion_change(S,origin_number,conversion);

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

五月的天气

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值