//栈做进制转换
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<stdlib.h>
#include<malloc.h>
using namespace std;
#define ERROR 0
#define OK 1
#define OVERFLOW 0
#define SIZE 50
#define ADD 20
typedef struct
{
int *base;
int *top;
int stacksize;
}Sqstack;
int init(Sqstack &S);
int push(Sqstack &S,int e);
int pop(Sqstack &S);
int conversion(Sqstack &S,int n,int m);
int main()
{
int n;
int m;
Sqstack S;
while(1)
{
cout<<"****输入要转换成的进制类型:2 or 8 or 16(输入0退出!)****\n";
cin>>n;
if(n==0)
break;
cout<<"输入十进制数:";
cin>>m;
conversion(S,n,m);
}
return 0;
}
int init(Sqstack &S)
{
S.base=(int *)malloc(SIZE*sizeof(int));
if(!S.base)exit(OVERFLOW);
S.top=S.base;
S.stacksize=SIZE;
return OK;
}
int push(Sqstack &S,int e)//**************************************************push
{
if(S.top-S.base>=S.stacksize){
S.base= (int *)realloc(S.base,(S.stacksize+ADD)*sizeof(int));
if(!S.base)exit(OVERFLOW);
S.top=S.base+S.stacksize;
S.stacksize+=ADD;
}
*S.top++=e;
return OK;
}
int pop(Sqstack &S)//*********************************************************pop
{ int e;
if(S.top==S.base)return ERROR;
e=*--S.top;
return e;
}
int conversion(Sqstack &S,int n,int m)
{
init(S);
int y;
while(1)
{
y=m%n;
push(S,y);
m=m/n;
if(m<n)
{
push(S,m);
break;
}
}
cout<<"结果:";
while(!(S.top==S.base))
{
int temp=pop(S);
if(temp<10)
cout<<temp;
else
printf("%c",temp+55);
}
cout<<endl;
return OK;
}
数据结构——栈
最新推荐文章于 2024-09-26 10:19:19 发布