栈-二进制转换为十进制

#include <stdio.h>
#include <stdlib.h>//malloc和realloc
#include <math.h>//平方的计算

#define STACK_INIT_SIZE 20//初始化栈的空间
#define STACKINCREMENT 10//扩展空间

typedef char ElemType;
//建立一个栈
typedef struct
{
    ElemType *base;//栈底
    ElemType *top;//栈顶
    int stackSize;//栈的容量
}sqStack;

//栈的初始化

void InitStack(sqStack *s)
{
    s->base=(ElemType *)malloc(STACK_INIT_SIZE *sizeof(ElemType));
    if(!s->base)
    {
        exit(0);
    }
    s->top=s->base;
    s->stackSize=STACK_INIT_SIZE;
}

//入栈
void Push(sqStack *s,ElemType e)//栈的名字,入栈的元素
{
    if(s->top - s->base >= s->stackSize)//判断栈是否满了
    {
        s->base=(ElemType *)realloc(s->base,(s->stackSize+STACKINCREMENT)*sizeof(ElemType));
        if(!s->base)
        {
            exit(0);
        }
    }
    *(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 s;
    int len,i,sum=0;

    InitStack(&s);//初始化

    printf("请输入二进制数,输入#符号表示结束!\n");
    scanf("%c",&c);
    if(c>49||c<48)
    {
        printf("输入有误!\n");

    }
    while(c != '#')
    {
        Push(&s,c);
        scanf("%c",&c);
    }
    getchar();//把'\n'从缓冲区去掉

    len=StackLen(s);
    printf("栈的当前容量是:%d\n",len);

    for(i=0;i<len;i++)
    {
        Pop(&s,&c);
        sum=sum+(c-48)*pow(2,i);
    }
    printf("转化为十进制数是:%d\n",sum);
    return 0;
}

你可能感兴趣的:(栈-二进制转换为十进制)