#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define STACK_ORIGINAL_SIZE 100
#define AUGMENTER_SIZE 10
typedef char Elemtype;
typedef struct{
Elemtype *top;
Elemtype *base;
int stackSize;
}sqStack;
//初始化栈
void initStack(sqStack *s)
{
s->base = (Elemtype*)malloc(STACK_ORIGINAL_SIZE*sizeof(Elemtype));
if(!s->base)
exit(0);
s->top = s->base;
s->stackSize = STACK_ORIGINAL_SIZE;
}
//进栈
void Puch(sqStack *s,Elemtype e)
{
//空间不足时,增加空间
if(s->top - s->base >= STACK_ORIGINAL_SIZE)
{
Elemtype *p;
p = (Elemtype*)realloc(s->base,(STACK_ORIGINAL_SIZE+AUGMENTER_SIZE)*sizeof(Elemtype));
if(!p)
{
free(s->base);
exit(0);
}
s->base = p;
s->top = s->base+STACK_ORIGINAL_SIZE;
s->stackSize = STACK_ORIGINAL_SIZE + AUGMENTER_SIZE;
}
*(s->top) = e;
(s->top)++;
}
//出栈
void Pull(sqStack *s,Elemtype *e)
{
//判断是否为空栈
if(s->base == s->top)
{
return;
}
*e = *--(s->top);
}
//栈的长度
int Stacklen(sqStack s)
{
return (s.top - s.base);
}
int main()
{
sqStack s;
Elemtype c;
initStack(&s);
int len,i,sum=0;
printf("请输入一个二进制数,输入#结束输入:");
scanf("%c",&c);
while(c!='#')
{
Puch(&s,c);
scanf("%c",&c);
}
getchar();
len = Stacklen(s);
printf("栈的当前容量是:%d\n",len);
for(i=0;i<len;i++)
{
Pull(&s,&c);
sum = sum + (c-48) * pow(2,i);
}
printf("输出的十进制为:%d\n",sum);
return 0;
}
二进制转化十进制(C语言栈)
最新推荐文章于 2023-10-23 15:02:42 发布