#include <stdio.h>
#define ERROR 0
#define OK 1
#define ElemType char
#define N 10
#define STACK_INIT_SIZE 100
#define STACKINCERMENT 10
typedef int status;
typedef struct
{
ElemType *top;
ElemType *base;
int stackSize;
}sqStack;
/*创建栈*/
status initStack(sqStack *s)
{
s->base=(ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
if(!s->base)
return ERROR;
s->top=s->base;
s->stackSize=STACK_INIT_SIZE;
return OK;
}
int Stacklen(sqStack s)
{
return ( s.top - s.base);
}
/*将一个数值放入栈顶*/
status Push(sqStack *s,ElemType e)
{
if( s->top - s->base >= s->stackSize)
{
s->base=(ElemType *)realloc(s->base,(s->stackSize+STACKINCERMENT) * sizeof(ElemType));
if(!s->base)
return ERROR;
s->top=s->base+s->stackSize;
s->stackSize=s->stackSize+STACKINCERMENT;
}
*(s->top)=e;
s->top++;
return OK;
}
/*从栈顶取出一个数*/
status Pop(sqStack *s,ElemType *e)
{
if(s->top == s->base)
return ERROR;
s->top--;
*e=*(s->top);
return OK;
}
/*------------栈清空---------*/
status ClearStack(sqStack *s)
{
s->top=s->base;
return OK;
}
int main()
{
int x,n,j,sum=0,lenth;
ElemType e;
sqStack s,q;
initStack(&s);
initStack(&q);
scanf("%c",&e);
while( e != '#')
{
Push(&s,e);
scanf("%c",&e);
}
getchar();
lenth=Stacklen(s);
x=lenth/3;
for(j=0;j<x;j++)
{
for(n=0;n<3; n++)
{
Pop(&s,&e);
sum=sum+(e-48)*pow(2,n);
lenth--;
}
Push(&q,(sum+48));
sum=0;
}
if( (x=lenth%3)>0)
{
for(n=0;n<x; n++)
{
Pop(&s,&e);
sum=sum+(e-48)*pow(2,n);
lenth--;
}
Push(&q,(sum+48));
}
lenth=Stacklen(q);
printf("the sum is:");
for(n=0;n<lenth;n++)
{
Pop(&q,&e);
printf("%c",e);
}
printf("\n");
return 0;
}
【数据结构与算法】栈的应用-二进制转八进制
最新推荐文章于 2022-07-30 14:46:49 发布