用栈进行进制转换
根据数据结构的算法。 可以将10进制转换为2-16进制
View Code
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char JJ[]={"0123456789ABCDEF"};
typedef struct node
{
struct node *next;
char data;
}stack;
int isEmpty(stack *s);
void CreatStack(stack **s);
void Push(stack **s,char x);
char Pop(stack **s);
void Convey(stack **s, int src, int dest);
int main()
{
int src,dest;
stack *s;
CreatStack(&s);
printf("请输入一个数字和要转换的进制: ");
scanf("%d %d",&src,&dest);
Convey(&s,src,dest);
return 0;
}
int isEmpty(stack *s)
{
return s->next == NULL;
}
void CreatStack(stack **s)
{
*s = (stack *)malloc(sizeof(stack));
if(*s == NULL)
{
printf("mermory error\n");
exit (0);
}
(*s)->next = NULL;
}
void Push(stack **s,char c)
{
stack *temp;
temp = (stack *)malloc(sizeof(stack));
if(temp == NULL)
{
printf("mermory error\n");
exit (0);
}
temp->data = c;
temp->next = (*s)->next;
(*s)->next = temp;
}
char Pop(stack **s)
{
stack *temp;
char x;
temp = (*s)->next;
x = temp->data;
(*s)->next = (*s)->next->next;
free(temp);
return x;
}
void Convey(stack **s, int src, int dest)
{
int temp, flag = 0;
char t;
if(src == 0)
{
Push(s,'0');
}
else
{
if(src < 0)
{
flag = 1;
src = - src;
}
while(src != 0)
{
temp = src % dest;
t = JJ[temp];
Push(s,t);
src /= dest;
}
}
if(flag == 1)
{
printf("-");
}
while( !isEmpty(*s))
{
t = Pop(s);
printf("%c",t);
}
printf("\n");
}