数据结构_栈实现数值转换

来源:互联网 发布:js调用身份证读取器 编辑:程序博客网 时间:2024/06/05 14:42

//明白了一些道理。。

#include
#include
#include
#include
#define STACK_INIT_SIZE 100
#define STACKCREMENT 10
#define N 8
typedef struct
{
    int*base;//栈底
    int*top;//栈顶
    intstacksize;//栈容量
}SqStack;
int InitStack(SqStack &S)
{
   S.base=(int*)malloc(STACK_INIT_SIZE*sizeof(int));
   if(!S.base)
    {
       exit(0);
    }
   S.top=S.base;
   S.stacksize=STACK_INIT_SIZE;
    return1;
}
int Push(SqStack &S,int e)
{
   if(S.top-S.base>=S.stacksize)
    {
       S.base=(int*)realloc(S.base,(S.stacksize+STACKCREMENT)*sizeof(int));
       if(!S.base)
       {
           exit(0);
       }
       S.top=S.base+S.stacksize;
       S.stacksize+=STACKCREMENT;
    }
   *S.top++=e;
    return1;
}
int StackEmpty(SqStack S)
{
   if(S.top==S.base)
    {
       return 1;
    }
    return0;
}
int Pop(SqStack &S,int &e)
{
   if(S.top==S.base)
    {
       return 0;
    }
   e=*--S.top;
    return1;
}
int main()
{
    intn,e;//n为要转换的十进制数,e为临时用的int变量
    SqStackS;
   InitStack(S);//构造一个空栈
   scanf("%d",&n);
   while(n)
    {
       Push(S,n%8);
       n/=8;
    }
   while(!StackEmpty(S))
    {
       Pop(S,e);
       printf("%d",e);
    }
   printf("\n");
    return0;
}