#include<stdio.h>
#include<stdlib.h> //malloc realloc函数头文件
#define STACK_INIT_SIZE 100//栈初始分配大小
#define STACKINCREAM 10 //栈内存扩展增量
typedef int ElemType;
typedef struct {
ElemType *base;
ElemType *top;
int stacksize; //栈当前大小
}SqStack;
void InitStack(SqStack *&s) //构造一个空战
{
s=(SqStack *)malloc(sizeof(SqStack)); //为栈结构指针分配存储空间
s->base=(ElemType *)malloc(STACK_INIT_SIZE*sizeof(ElemType));//栈底指针指向一片内存
if(!s->base) //存储空间分配失败,结束进程
exit(-1);
s->top=s->base;
s->stacksize=STACK_INIT_SIZE;
}
void Push(SqStack *&s,ElemType e) //入栈操作
{
if(s->top-s->base>=s->stacksize) //栈满情况
{
s->base=(ElemType *)realloc(s->base,(s->stacksize+STACKINCREAM)*sizeof(ElemType));//realloc函数拓展空间且不改变原空间内容
if(!s->base)
exit(-1);
s->top=s->base+s->stacksize;
s->stacksize+=STACKINCREAM;
}
*s->top++=e; //压栈操作
}
void Pop(SqStack *&s,int e)//出栈
{
e=* --s->top;
printf("%d",e);
}
int main() //通过栈的结构来进行进制转换
{
SqStack *s;
int n,m,e;
printf("请输入一个十进制数和预转换成的进制数:\n");
while(scanf("%d%d",&n,&m)!=EOF)
{
InitStack(s);
while(n)
{
Push(s,n%m);
n=n/m;
}
while(s->top!=s->base)
{
Pop(s,e);
}
printf("\n");
printf("请输入一个十进制数和预转换成的进制数:\n");
}
return 0;
}
利用栈实现进制转换!!!
最新推荐文章于 2024-01-28 01:00:19 发布