利用栈的特性,将十进制数转换成八进制数

栈的特定是:先进后出

源程序:

//这个程序的目的是让用户输入一个十进制数,然后打出这个数的八进制数
#include<iostream>
using namespace std;
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define STACK_INIT_SIZE  200
#define STACKINCREMENT 10
typedef int SElemType;
typedef struct
{
SElemType *base;
SElemType *top;
int stackSize;


}SqStack;
int InitStack(SqStack *S)
{
S->base=(SElemType*)malloc(STACK_INIT_SIZE*sizeof(SElemType));
if(!S->base)
{
        return ERROR;
}
S->top=S->base;
S->stackSize=STACK_INIT_SIZE;
return OK;
}
int Push(SqStack *S,SElemType e)
{
if(S->top-S->base>=S->stackSize)
{
S->base=(SElemType *)realloc(S->base,(S->stackSize+STACKINCREMENT)*sizeof(SElemType));
if(!S->base)
exit(OVERFLOW);
S->top=S->base+S->stackSize;
S->stackSize=S->stackSize+STACKINCREMENT;


}
*(S->top++)=e;
return OK;
}
int Pop(SqStack *S,SElemType *x)
{
if(S->top==S->base)
return ERROR;
*x=*(--S->top);
return OK;
}
int stackEmpty(SqStack *S)
{
if(S->base==S->top)
return OK;
else
return ERROR;


}
void conversion()
{
int N;
cout<<"请输入一个非负整数:"<<endl;
cin>>N;
    SqStack S;
//构造一个空的栈
InitStack(&S);
while(N)
{
Push(&S,N%8);
N=N/8;
}
//然后从栈顶元素一个一个的将元素输出
    SElemType x;
cout<<"转换之后的八进制数: ";
while(!stackEmpty(&S))
{
Pop(&S,&x);
cout<<x;
}
cout<<endl;
}
int main()
{
conversion();
return 0;
}


阅读更多
换一批

没有更多推荐了,返回首页