栈的应用-进制转换

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define IncreSize 10
#define InitSize 10

typedef int status;
typedef char Elemtype;

typedef struct sStack
{
Elemtype *base;
Elemtype *top;
int StackSize;
}sqStack;

void InitStack(sqStack *s)
{
s->base = (Elemtype *)malloc(sizeof(int)*InitSize);
if(!s->base)
exit(0);
else
{
s->top = s->base;
s->StackSize = InitSize;
//return OK;
}
}

void Push(sqStack *s, Elemtype e)
{
if(s->top - s->base >= s->StackSize)
{
s->base = (Elemtype *)realloc(s->base,(s->StackSize + IncreSize)*sizeof(Elemtype)); //这里申请的大一些的空间;
if(!s->base)
exit (0);
}
*(s->top) = e;
s->top++;
//return OK;
}

void Pop(sqStack *s, Elemtype *e)
{
if(s->top == s->base)
exit(0);
*e = *--(s->top);
// return OK;
}

int StackLen(sqStack s)
{
return(s.top - s.base); //注意这里的结果是栈中的数据个数;
}

int main()
{
Elemtype c,e,r;
sqStack s,t;
int i,len1,len2,sum = 0;
InitStack(&s);
InitStack(&t);
scanf("%c",&c);
while(c != '#')
{
Push(&s,c);
scanf("%c",&c);
}
len1 = StackLen(s);    //在这里如果是换成for(i = 0; i < StackLen(s); i++)就会出现错误,原因也不是很清楚。。。

getchar();        //这里加这句代码的原因是为了在这里不把回车键放入键盘缓冲区内。


/* for(i = 0; i < len; i++)
{
Pop(&s,&e);
//printf("%d ",e);
sum = sum + ((e-48) * pow(2,i));
}
printf("%d\n",sum);
*/


/*for(i = 0; i < len; i++) //转换为8进制;有问题,参照16进制
{
Pop(&s,&e);
sum = sum + (e - 48) * pow(2,i%3);
if(i % 3 == 2)
{
printf("%d",sum);
sum = 0;
}
}
*/

for(i = 0; i < len1; i++) //转换为16进制;
{
Pop(&s,&e);
sum = sum + (e - 48) * pow(2,i%4);
if(i % 4 == 3)
{
Push(&t, sum);
sum = 0;
}
}

len2 = StackLen(t);

for(i = 0; i < len2; i++)
{
Pop(&t, &r);
printf("%d",r);
}
printf("\n");

return 0;
}





 

posted on 2015-01-27 00:50  liu168aad  阅读(207)  评论(0编辑  收藏  举报