/*数序栈*/
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define SElemType char
#define STACK_INIT_SIZE 100
#define STACK_INCREMENT 10
#define OK 1
#define ERROR -1
#define Status int
#define OVER -1
/*栈空 top == base
**栈满 top-base = stacksize
**
*/
typedef struct
{
SElemType *
base;
SElemType *
top;
int stacksize;
int length;
}SqStack;
/*数序栈结构*/
/*栈的初始化*/
Status initSqStack(SqStack *
s)
{
s->
base = (SElemType*)malloc(STACK_INIT_SIZE *
sizeof(SElemType));
if(! s->
base)
return OVER;
s->top = s->
base;
s->stacksize =
STACK_INIT_SIZE;
s->length =
0;
return OK;
}
Status pushSqStack(SqStack *s,
const SElemType item)
{
/* stack full*/
if(s->top - s->
base ==
STACK_INIT_SIZE)
{
s->
base = (SElemType*)realloc(s->
base,(STACK_INCREMENT+STACK_INIT_SIZE)*
sizeof(SElemType));
if(!s->
base)
return OVER;
s->top = s->
base+ s->
stacksize;
s->stacksize +=
STACK_INCREMENT;
}
*s->top++ =
item;
return OK;
}
Status popSqStack(SqStack *s,SElemType *
item)
{
if(s->top == s->
base)
return ERROR;
*item = *--(s->
top);
return OK;
}
/*获取栈长度*/
int lengthSqStack(SqStack *
s)
{
return s->top-s->
base;
}
int main(
void)
{
SElemType data;
SqStack s;
int len,i,sum =
0;
printf("Please input a binary digit\n");
initSqStack(&
s);
scanf("%c",&
data);
while(data !=
'#')
{
pushSqStack(&
s,data);
scanf("%c",&
data);
}
getchar();
len = lengthSqStack(&
s);
for(i =
0;i<len;i++
)
{
popSqStack(&s,&
data);
printf("%c",data);
sum += (data-
48)*pow(
2,i);
}
printf("Decimal is :%d.\n",sum);
getchar();
return 0;
}
转载于:https://www.cnblogs.com/plxx/p/3489187.html
相关资源:数据结构—成绩单生成器