/*
用栈实现的数值转换
*/
#include<stdio.h>
#include<malloc.h>
typedef int Datatype;
typedef struct stacknode
{
Datatype data;
struct stacknode *next;
}StackNode;
typedef struct
{
StackNode *top;//栈顶指针
}LinkStack;
//置栈空
void Initial(LinkStack *s)
{
s->top=NULL;
}
//判栈空
int IsEmpty(LinkStack *s)
{
return s->top==NULL;
}
//进栈
void push(LinkStack *s,Datatype x)
{
StackNode *p=(StackNode *)malloc(sizeof(StackNode));
p->data=x;
p->next=s->top;
s->top=p;
}
//退栈
Datatype pop(LinkStack *s, Datatype x)
{
StackNode *p=s->top;//保存指针
while (IsEmpty(s))
{
printf("栈为空");//下溢
exit(1);
}
x=p->data;
s->top=p->next;
free(p);
return x;
}
LinkStack * CgData(LinkStack *p,Datatype Num,Datatype N)
{ //数值转换
LinkStack *head;
Datatype counter;
Initial(p);
while(Num)
{
//Num=Num/N;
counter=Num%N;
if(counter>9)
counter+=55;
push(p,counter);
Num=Num/N;
}
head=p;
return head;
}
void print(LinkStack *head)
{
StackNode *p;
Datatype e,data;
p=head->top;
while (!IsEmpty(head))
{
data=pop(head,e); //出栈并返回栈顶元素
if(data<10)
printf("%d",data);
else
printf("%c",data);
}
printf("\t");
}
int main()
{
LinkStack *p;
LinkStack *head;
Datatype i,j,e,N;
printf("请输入数值:");
scanf("%d",&N);
printf("十进制\t二进制\t八进制\t十六进制\t\n");
for(i=1;i<=N;i++)
{
printf("%d\t",i);
for(j=2;j<=8;j*=4)//转制二进制和八进制数据
{
head=CgData(p,i,j);
print(head);
}
head=CgData(p,i,16);//转制十六进制数据
print(head);
printf("\n");
}
getchar();
return 0;
}