用栈实现十进制向八进制(二进制)的转换
#include"stdio.h"#include "stdlib.h"
#include"math.h"
#define ok 1
#define error 0
#define overflow -1
typedef int status;
typedef int selemtype;
#define stack_init_size 100
#define stackincrement 10
typedef struct sqstack
{
selemtype * base;
selemtype * top;
int stacksize;
}sqstack;
status initstack(sqstack *s)
{
(*s).base=(selemtype *)malloc(stack_init_size *sizeof(selemtype));
if(!(*s).base) exit (overflow);
(*s).top=(*s).base;
(*s).stacksize=stack_init_size;
return ok;
}
status stackempty(sqstack s)
{
if(s.top==s.base)
return ok;
else
return error;
}
status 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+=stackincrement;
}
*((*s).top)++=e;
return ok;
}
status pop(sqstack *s,selemtype *e)
{
if((*s).top==(*s).base)
return error;
*e=*--(*s).top;
return ok;
}
main()
{
sqstack s;
selemtype e;
int N;
initstack(&s);
scanf("%d",&N);
while(N)
{
push(&s,N%2); // 如果转换为八进制 将2改为8即可 下同
N=N/2;
}
while(!stackempty(s))
{
pop(&s,&e);
printf("%d",e);
}
}