#include"stdio.h"
#include"stdlib.h"
#define MAXSIZE 100
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int SElemType;
typedef int Status;
typedef struct
{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;//顺序栈
Status Init_Stack(SqStack &S){
S.base=(SElemType *)malloc(MAXSIZE*sizeof(SElemType));
if(!S.base)return OVERFLOW;
S.top=S.base;
S.stacksize=MAXSIZE;
return OK;
}
//进栈
Status Push(SqStack &S,SElemType e){
if(S.top-S.base>=S.stacksize)return ERROR;
*S.top=e;
S.top++;
return OK;
}
//出栈
Status Pop(SqStack &S,SElemType &e){
if(S.base==S.top)return ERROR;
S.top--;
e=*S.top;
return OK;
}
int main(){
SqStack S;
int a,i,e;
if(Init_Stack(S)==1){
printf("栈初始化成功。。。\n");
printf("请输入一个十进制整数:");
scanf("%d",&a);
while(a){
i=a%2;
a=a/2;
Push(S,i);
}
printf("该数的二进制为:");
while(S.base!=S.top){
Pop(S,e);
printf("%d",e);
}
}
else{
printf("栈初始化失败。。。\n");
}
return 0;
}
【数据结构】利用栈实现将一个十进制数转化为二进制数
最新推荐文章于 2024-07-03 18:58:50 发布