单向链栈实现进制转换(十进制转换成N进制数【正数】)

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

//数据节点结构体定义
typedef struct numNode
{
	int data;
	struct numNode *next;
}numNode;

//栈结构定义
typedef struct
{
	int length;
	numNode *end;
}numStack;

numStack * initNumStack();			//创建并初始化栈
void push(numStack *stack, int num);		//入栈操作
numNode * pop(numStack *stack);			//出栈操作
void destroy(numStack *stack);			//栈的销毁
void display(numStack *stack);			//栈的打印
char num_to_char(const int num);		//数字转换成字符
numStack * convert(int num, const int radix);	//十进制数num转换成radix进制数

//创建并初始化空栈
numStack * initNumStack()
{
	numStack *stack = (numStack *)malloc(sizeof(numStack));
	if (NULL == stack)
		exit(-1);
	stack->length = 0;
	stack->end = NULL;
	return stack;
}

//压栈操作
void push(numStack *stack, int num)
{
	if (NULL == stack)
		exit(-1);
	numNode *num_node = (numNode *)malloc(sizeof(numNode));
	num_node->data = num;
	if (NULL == num_node)
		exit(-1);
	num_node->next = stack->end;
	stack->end = num_node;
	++stack->length;
}

//出栈操作
numNode * pop(numStack *stack)
{
	numNode *node_tmp = NULL;
	if (NULL == stack || 0 == stack->length)
		return NULL;
	node_tmp = stack->end;
	stack->end = node_tmp->next;
	--stack->length;
	return node_tmp;
}

//销毁栈
void destroy(numStack *stack)
{
	numNode * tmp = NULL;
	while(NULL != (tmp = pop(stack)))
		free(tmp);
	if(stack)
		free(stack);
}

//打印栈数据
void display(numStack *stack)
{
	numNode * tmp = NULL;
	if (stack)
	{
		tmp = stack->end;
		while(tmp)
		{
			printf("%c ", num_to_char(tmp->data));
			tmp = tmp->next;
		}
		printf("\n");
	}
}

//数字转换成字符
char num_to_char(const int num)
{
	if(num < 10)
		return '0'+num;
	else
		return 'A'+num-10;
}

//十进制转换成n进制的实现函数
numStack * convert(int num, const int radix)
{
	numStack *stack = initNumStack();
	while (num)
	{
		push(stack, num%radix);
		num /= radix;
	}
	return stack;
}

int main()
{
	numStack * resoult = convert(128, 7);
	display(resoult);
	destroy(resoult);
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值