码迷,mamicode.com
首页 > 其他好文 > 详细

利用栈实现进制转换

时间:2018-08-15 20:37:37      阅读:322      评论:0      收藏:0      [点我收藏+]

标签:err   code   静态   oid   ror   printf   ret   main   array   

#include<stdio.h>
#include<malloc.h>

#define MAX_STACK_SIZE 10//静态栈向量大小

#define ERROR 0
#define OK 1

typedef int ElemType;
typedef int Status;
/
栈的应用:
进制转换
/
typedef struct sqstack{
ElemType stack_array[MAX_STACK_SIZE];
// int size;
int top;
int bottom;
}SqStack;

//初始化栈
void Init_Stack(SqStack *S){
S->bottom=S->top=0;
printf("\n初始化栈成功!\n");
}

//压栈(元素进栈)
Status push(SqStack *S , ElemType e){
if(S->top >= MAX_STACK_SIZE - 1){
printf("栈满!\n");
return ERROR;//栈满
}
printf("--------");
printf("当前入栈元素:%d\n",e);
// printf("入栈前S->top==%d\n",S->top);
S->top++;//位置自加
// S->size++;
// printf("size==%d",S->size);
printf("入栈后S->top==%d\n",S->top);
S->stack_array[S->top] = e;//元素入栈
return OK;
}

//弹栈(元素出栈)
Status pop(SqStack *S , ElemType e){
if(S->top == 0){
return ERROR;//栈空
}
e = S->stack_array[S->top];//先取
printf("当前应当出栈:%d\n",e);
S->top--;//自减
// S->size--;
// printf("size==%d",S->size);
return OK;
}

//遍历栈
Status StackTravel(SqStack *S){
int e;
int ptr;
ptr = S->top;

while(ptr > S->bottom){
    e = S->stack_array[ptr];
    ptr--;
    printf("%d",e);
}

}

void conversion(int n , int d){
SqStack S;//创建栈
ElemType k;//欲进栈的元素
int temp = n;//保存n
Init_Stack(&S);//初始化栈
// printf("--入栈初始:S->top==%d\n",S.top);
while(n>0){
k = n % d;//取余
push(&S,k);//余数进栈
n = n / d;//结果取整
}
printf("将%d转化成%d进制后为:",temp,d);
StackTravel(&S);//遍历栈
}

int main(){
conversion(511, 2);
conversion(512, 2);
}

利用栈实现进制转换

标签:err   code   静态   oid   ror   printf   ret   main   array   

原文地址:http://blog.51cto.com/12012875/2160421

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!