用栈将十进制数转化为二进制数,要求用C语言实现,希望能有详细的代码,谢谢

2025-02-23 19:48:50
推荐回答(2个)
回答1:

#include

typedef struct
{
int *base;
int stacksize;
int *top;
}sqstack;

void initstack(sqstack *S)
{

(*S).base=(int *)malloc(sizeof(int)*10);
if(!(*S).base) exit(0);
(*S).stacksize=10;
(*S).top=(*S).base;

}

int pop(sqstack *S)
{int e;
if((*S).base==(*S).top) exit(0);
e=*(--(*S).top);

return e;

}

void push(sqstack *S,int e)
{
if((*S).top-(*S).base>=(*S).stacksize)
{
(*S).base=(int*)realloc((*S).base,sizeof(int)*((*S).stacksize+1));
if(!(*S).base) exit(0);
(*S).top=(*S).base+(*S).stacksize;
(*S).stacksize++;

}
*(*S).top=e;
(*S).top++;

}
int StackEmpty(sqstack *S)
{
if((*S).top==(*S).base)
return 0;

}

main()
{
int i,e;
sqstack S;
initstack(&S);
scanf("%d",&i);
while(i)
{
push(&S,i%2);//调用入栈函数,具体的函数自己写
i=i/2;

}
while(StackEmpty(&S))//判断堆栈是否为空
{
e=pop(&S);//出栈
printf("%d",e);

}

}

回答2: