#include <stdio.h>
#include <stdlib.h>
#define STACK_INIT_SIZE 20
#define STACKINCREMENT 10
typedef char ElemType;
typedef struct{
ElemType *base;
ElemType *top;
int size;
}sqStack;
int wd_pow(int i, int j){
int a, num = 1;
for (a = 0; a < j; a++){
num *= i;
}
return num;
}
void InitStack(sqStack *s){//初始化
s->base = (ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
if (!s->base ){
exit (0);
}
s->top = s->base;
s->size = STACK_INIT_SIZE;
}
void push(sqStack *s, ElemType e){//入栈
if (s->top - s->base >= s->size){
s->base = (ElemType *)realloc(s->base, (s->size + STACKINCREMENT) * sizeof(ElemType));
if (!s->base ){
exit (0);
}
s->top = s->base + s->size;
s->size = s->size + STACKINCREMENT;
}
*(s->top) = e;
s->top++;
}
void pop(sqStack *s, ElemType *e){//弹栈
if (s->top == s->base){
return;
}
*e = *--(s->top);
}
int StackLen(sqStack s){//求栈当前容量
return (s.top - s.base);
}
int main(){
ElemType c;
sqStack s1, s2;
int len, i, j, sum = 0;
InitStack (&s1);//初始化栈s1,用来存放二进制输入
printf("请输入二进制数,输入#表示结束! \n");
scanf("%c", &c);
while(c != '#'){
if (c == '0' || c == '1' )//检查输入是否二进制
push(&s1, c);
scanf("%c", &c);
}
getchar ();//把\n从缓冲区去掉
len = StackLen(s1);
InitStack(&s2); // 初始化栈s2,用来存放转换的八进制
printf("栈的当前容量是:%d\n", len);
for(i = 0; i < len; ){
for(j = 0; j < 3; j++, i++){
pop(&s1, &c);
sum = sum + (c-48) * wd_pow(2, j);
if (s1.base == s1.top){
break;
}
}
push(&s2, sum+48);
sum =0;
}
printf("转换为八进制是:");
while (s2.base != s2.top){
pop(&s2, &c);
putchar(c);
}
putchar('\n');
return 0;
}
|