|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define Stacksize 20
#define stacksizeplus 10
typedef char ElemType;
struct stack{
ElemType *base;
ElemType *top;
int stacksize;
};
void InitStack(struct stack *s)
{
s->base=(ElemType*)malloc(Stacksize*sizeof(ElemType));
if(!s->base)
{
exit(0);
}
s->top=s->base;//栈底指针和栈顶指针在初始时指向同一位置
s->stacksize=Stacksize;
}
void Push(struct stack *s,ElemType *e)//压栈函数,插入元素e为新的栈顶元素
{
if(s->top-s->base>=s->stacksize)
{
s->base=(ElemType*)realloc(s->base,(s->stacksize+stacksizeplus)*sizeof(ElemType));
}
if(!s->base)
{
exit(0);
}
s->top=s->base+s->stacksize;
*(s->top)=e;
s->top++;
}
void Pop(struct stack *s,ElemType *e)
{
if(s->top==s->base)
{
return;
}
*e=*--(s->top);
}
int StackLength(struct stack s)
{
return (s.top - s.base);
}
int main()
{
ElemType c;
struct stack s;
int i,len,sum=0;
InitStack(&s);
printf("请用户输入二进制数,输入#表示结束!\n");
scanf("%c",&c);
while(c!='#')
{
Push(&s,c);
scanf("%c",&c);
}
getchar();//把'\n'从缓冲区去掉,即取消回车这个字符带来的影响
len=StackLength(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;
}
|
|