写出利用栈将一个十进制整数转化为二进制数的算法

我们的作业题~~谢谢大家帮忙~~~

第1个回答  2008-04-24
#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define LISTINCREMENT 10
#define INFEASIBLE -1
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef int SElemType;
typedef int Status;
typedef int ElemType;
typedef struct SqStack
{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;

Status InitStack(SqStack &S);
Status Push(SqStack &S,SElemType e);
Status Pop(SqStack &S,SElemType &e);
Status StackEmpty(SqStack S);
void convert(int a);
void main()
{
int n,M,e;
SqStack S;
InitStack(S);
printf("请输入要转换的数字:");
scanf("%d",&n);
M=n;
while(M)
{
Push(S,M % 2);
M = M / 2;
}
printf("转换为二进制数为:");
while(!StackEmpty(S))
{
Pop(S,e);
printf("%d",e);
}
printf("\n");

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 Pop(SqStack &S,SElemType &e)
{
if(S.top == S.base)
return ERROR;
e = *--S.top;
return OK;
}

Status Push(SqStack &S,SElemType e)
{
if(S.top - S.base >= S.stacksize)
{
S.base = (ElemType *)realloc(S.base,(S.stacksize + LISTINCREMENT) * sizeof(ElemType));
if(!S.base)
exit(OVERFLOW);
S.top = S.base + S.stacksize;
S.stacksize += STACKINCREMENT;
}
*S.top++ = e;
return OK;
}

Status StackEmpty(SqStack S)
{
if(S.top == S.base)
return OK;
else
return ERROR;
}

void convert(int e)
{
if(e==0)
printf("0");
if(e==1)
printf("1");
}本回答被提问者采纳
相似回答