进制转换
头文件
#ifndef __HEAD_H__
#define __HEAD_H__
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef int datatype;
typedef struct Node
{
union
{
int len;
datatype data;
};
struct Node *next;
}*linkstack;
linkstack create_stack();
linkstack create_node();
int linkstack_push(linkstack top,datatype e);
void output_stack(linkstack top);
int delete_stack(linkstack top);
linkstack free_stack(linkstack top);
int ten_two(linkstack top ,int n);
int ten_sixteen(linkstack top ,int n);
void output_stack16(linkstack top);
#endif
自定义函数
#include"head.h"
/*
* function:
* @param [ in]
* @param [out]
* @return
*/
linkstack create_stack()
{
linkstack top = (linkstack)malloc(sizeof(struct Node));
if(top == NULL)
return NULL;
top->len = 0;
top->next = NULL;
return top;
}
/*
* function:
* @param [ in]
* @param [out]
* @return
*/
linkstack create_node()
{
linkstack p= (linkstack)malloc(sizeof(struct Node));
if(p == NULL)
return NULL;
p->len = 0;
p->next = NULL;
return p;
}
/*
* function: 链栈的入栈
* @param [ in] 栈头,元素
* @param [out]
* @return 成功返回0;失败返回-1
*/
int linkstack_push(linkstack top,datatype e)
{
linkstack p = create_node();
if(top == NULL||p == NULL)
{
printf("入栈失败\n");
return -1;
}
p->data = e;
p->next = top->next;
top->next = p;
top->len++;
return 0;
}
/*
* function: 链栈的输出
* @param [ in] 链栈
* @param [out]
* @return 无
*/
void output_stack(linkstack top)
{
if(top == NULL||top->len == 0)
{
printf("输出失败\n");
return ;
}
linkstack p = top;
while(p->next)
{
p = p->next;
printf("%d\t",p->data);
}
puts("");
}
/*
* function: 链栈的删除(头删)
* @param [ in] 链栈
* @param [out]
* @return 成功返回0;失败返回-1
*/
int delete_stack(linkstack top)
{
if(top == NULL || top->len == 0)
{
printf("删除失败\n");
return -1;
}
linkstack p = top->next;
top->next = p->next;
free(p);
p = NULL;
top->len--;
return 0;
}
/*
* function: 释放空间
* @param [ in] 链栈
* @param [out]
* @return 返回 NULL
*/
linkstack free_stack(linkstack top)
{
if(top == NULL)
return NULL;
int flag ;
while(flag == 0)
{
flag = delete_stack(top);
}
free(top);
top = NULL;
return top;
}
/*
* function: 进制转换(十进制转二进制)
* @param [ in] 链表,十进制数
* @param [out]
* @return 成功返回0,失败返回-1
*/
int ten_two(linkstack top ,int n)
{
while(n)
{
datatype i = n%2 ;
linkstack_push(top,i);
n /= 2;
}
}
/*
* function: 进制转换(十进制转十六进制)
* @param [ in] 链表,十进制数
* @param [out]
* @return 成功返回0,失败返回-1
*/
int ten_sixteen(linkstack top ,int n)
{
while(n)
{
datatype i = n%16 ;
linkstack_push(top,i);
n /= 16;
}
}
/*
* function: 链栈的输出十六进制
* @param [ in] 链栈
* @param [out]
* @return 无
*/
void output_stack16(linkstack top)
{
if(top == NULL||top->len == 0)
{
printf("输出失败\n");
return ;
}
linkstack p = top;
while(p->next)
{
p = p->next;
printf("%#x\t",p->data);
}
puts("");
}
主函数
#include"head.h"
int main(int argc, const char *argv[])
{
linkstack top = create_stack();
int n;
printf("输入十六进制数:");
scanf("%d",&n);
// ten_two(top,n);
// output_stack(top);
ten_sixteen(top ,n);
output_stack16(top);
free_stack(top);
return 0;
}