用栈实现十六进制转换为十进制
数据结构上机报告
班 级信科2班学 号19姓 名李柏威
实验内容:利用栈的基本操作,写一个C程序实现将十进制数转化为十六进制数
实验目的:掌握栈的操作
提交内容:
C语言源代码:
#include
#include
#define INITSIZE 100
#define INCREMENT 10
typedef char SElemType;
typedef struct stack{
SElemType *base;
SElemType *top;
int stacksize;
}stack;
void initstack(stack &s)//初始化栈
{
s.base=(SElemType *)malloc(INITSIZE*sizeof(SElemType));
if(!s.base)
exit(0);
s.top=s.base;
s.stacksize=INITSIZE;
}
void Push(stack &s,SElemType e)//入栈,栈满则追加栈空间
{
if(s.top-s.base>=INITSIZE)
{
s.base=(SElemType *)realloc(s.base,(s.stacksize+INCREMENT)*sizeof(SElemType));
if(!s.base)
exit(0);
s.top=s.base+s.stacksize;
s.stacksize+=INCREMENT;
}
*s.top++=e;
}
void Pop(stack &s,SElemType &e)//出栈
{
if(s.base==s.top)
printf("出错了!");
else
e=*--s.top;
}
int stackEmpty(stack &s)//判栈空
{
if(s.base==s.top)
return 1;
else return 0;
}
void conversion(int n)//进制转换
{
char A,B,C,D,E,F;
char e;
stack s;
initstack(s);
while(n)
{
Push(s,n%16);
n=n/16;
}
while(!stackEmpty(s))
{
Pop(s,e);
if(e<10)printf("%d",e);
if(e==10)printf("A");
if(e==11)printf("B");
if(e==12)printf("C");
if(e==13)printf("D");
if(e==14)printf("E");
if(e==15)printf("F");
}
}
int main()
{
int n;
while(n!=0)//连续输入0退出
{
printf("请输入十进制数:");
scanf("%d",&n);
printf("转化后的十六进制数是:");
conversion(n);
printf("\n\n");
}
}程序执行结果截图界面: