c语言顺序栈的应用(实战篇-进制转换)

直接附上二进制转十进制的代码

//二进制转十进制,利用栈的FILO(先进后出)的特点
#include
#include
#include
#define OK     1
#define ERROR  0
#define STACK_INIT_SIZE 2
#define STACKINCREMENT  3
typedef int Status;
typedef char SElemType;
typedef struct{
    SElemType *top;
    SElemType *base;
    int stacksize;
}sqStack;
Status StackInit(sqStack *s){
    s->base = (SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType));
    if(!s->base)
        return ERROR;
    s->top = s->base;
    s->stacksize = STACK_INIT_SIZE;
    return OK;
}
void Push(sqStack *s,SElemType e){
    if(s->top - s->base >= s->stacksize){//必须是大于等于
        s->base = (SElemType *)realloc(s->base,(s->stacksize+STACKINCREMENT)*sizeof(SElemType));
        if(!s->base){
            exit(0);
            printf("增容失败.....");
        }
        printf("增容......\n");
        s->top = s->base + s->stacksize;
        s->stacksize += STACKINCREMENT;
    }
    *(s->top) = e;
    s->top++;
}
void Pop(sqStack *s,SElemType *e){
    if(s->top == s->base){
        return;
    }
    *e = *--(s->top);
}
int StackLength(sqStack *s){
    return (s->top - s->base);
}
int main(){
    sqStack s;
    SElemType e;
    StackInit(&s);
    printf("请输入一串二进制数字,以#作为结束标志..\n");
    scanf("%c",&e);
    while(e != '#'){
        Push(&s,e);
        scanf("%c",&e);
    }
    getchar();	//比如我们输入11001001#然后回车,回车ASCII码的值是10,对下一次输入产生影响
    int len=0;
    int sum=0;    //要赋初始值,尝试不赋初始值,我的电脑上是42,不知道为什么
    //printf("suum=%d",sum);
    len = StackLength(&s);
    printf("栈的容量:%d\n",len);
    printf("\n");
    for(int i=0;i<len;i++){
        Pop(&s,&e);
        sum += (e-48)*pow(2,i);//因为传%c时候,0的值是48,1的值是49.
    }
    printf("转化为十进制为:%d\n",sum);
    return 0;
}

运行结果:

请输入一串二进制数字,以#作为结束标志..
11001001#
增容......
增容......
栈的容量:8

转化为十进制为:201

Process returned 0 (0x0)   execution time : 4.358 s
Press any key to continue.

你可能感兴趣的:(数据结构)