用链栈解决正整数进制转换问题(C语言)

输入一个十进制正整数,再输入要转换到的进制。

输出结果。

使用链栈

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

typedef int datatype;

typedef struct LinkStack
{
	datatype data;
	struct LinkStack* next;
}LinkStack, *pLinkStack;

void initLinkStack(pLinkStack* p_link_stack)
{
	*p_link_stack = NULL;
}

bool isEmptyLinkStack(pLinkStack p_link_stack)
{
	if (!p_link_stack)
		return true;

	return false;
}

bool pushLinkStack(pLinkStack* p_link_stack, datatype push_data)
{
	pLinkStack p_new = calloc(1, sizeof(LinkStack));
	if (!p_new)
		return false;

	p_new->data = push_data;
	p_new->next = *p_link_stack;
	*p_link_stack = p_new;
	return true;
}

bool popLinkStack(pLinkStack* p_link_stack, datatype* pop_data)
{
	if (isEmptyLinkStack(*p_link_stack))
		return false;

	*pop_data = (*p_link_stack)->data;
	pLinkStack p_temp = *p_link_stack;
	*p_link_stack = (*p_link_stack)->next;
	free(p_temp);
	p_temp = NULL;
	return true;
}

void conversion(int number1, int number2)
{
	pLinkStack p_link_stack = NULL;
	initLinkStack(&p_link_stack);

	while (number1)
	{
		if (!pushLinkStack(&p_link_stack, number1 % number2))
		{
			printf("Can NOT Allocate Memory\n");
			return;
		}
		number1 = number1 / number2;
	}
	
	datatype temp = 0;
	while (popLinkStack(&p_link_stack, &temp))
	{
		printf("%d", temp);
	}
	puts("");
}

int main()
{
	int number1, number2;
	printf("Please Input a Decimal Integer:\n");
	scanf("%d", &number1);

	printf("Please Input a System Number:\n");
	scanf("%d", &number2);

	printf("The Result is:\n");
	conversion(number1, number2);

	return 0;
}

方法解决。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值