#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef char ElemType;
typedef struct
{
int maxsize;
ElemType *top;
ElemType *base;
}SqStack;
void init(SqStack* s, int n)
{
s->base = (ElemType*)malloc(sizeof(ElemType)*n);
if( !s->base )
{
exit(0);
}
s->maxsize = n;
s->top = s->base;
}
void push(SqStack* s, ElemType a)
{
if(s->top - s->base == s->maxsize)
{
printf("栈满!\n");
exit(0);
}
*s->top++ = a;
}
void pop(SqStack* s,ElemType *e)
{
if(s->top == s->base)
{
printf("栈已空\n");
return;
}
*e = *--s->top;
}
int StackLen(SqStack s)
{
return (s.top-s.base);
}
int main()
{
ElemType c;
SqStack s;
int len,i,sum = 0;
init(&s,20);
printf("请输入二进制整数。\n");
scanf("%c",&c);
while( c != '\n')
{
push(&s,c);
scanf("%c",&c);
}
len = StackLen(s);
for(i = 0;i < len;i++)
{
pop(&s,&c);
sum = sum + (c-48) * pow(2,i);
}
printf("%d",sum);
getchar();
return 0;
}
栈的简单应用
于 2022-03-19 22:04:17 首次发布