您的位置:首页 > 其它

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

2014-02-23 10:54 501 查看
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  结构 malloc