|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <malloc.h>
#include <math.h>
#define STACK_INIT_SIZE 20
#define STACK_INCREMENT 10
#define BIN2OCT 0
#define BIN2DEC 1
#define BIN2HEX 0
typedef char Elemtype;
typedef struct
{
Elemtype *base;
Elemtype *top;
int stackSize;
}sqStack;
void InitStack(sqStack *s)
{
s->base = (Elemtype *)malloc(STACK_INIT_SIZE * sizeof(Elemtype));
if(!s->base)
{
exit(0);
}
s->top = s->base;
s->stackSize = STACK_INIT_SIZE;
}
void Push(sqStack *s,Elemtype e)
{
if(s->top - s->base >= s->stackSize)
{
s->base = (Elemtype *)realloc(s->base,(s->stackSize + STACK_INCREMENT) * sizeof(Elemtype));
if(!s->base)
{
exit(0);
}
}
*(s->top) = e;
s->top++;
}
void Pop(sqStack *s,Elemtype *e)
{
if(s->top == s->base)
{
return;
}
*e = *--(s->top);
}
int StackLen(sqStack s) //会对数据进行修改就传入指针,不会则传入地址就可以了
{
return (s.top - s.base);
}
int main(void)
{
Elemtype c;
sqStack bin,oct,hex;
int i,len,sum = 0;
InitStack(&bin);
printf("请输入二进制数,以'#'结束!\n");
scanf("%c",&c);
while(c != '#')
{
Push(&bin,c);
scanf("%c",&c);
}
getchar(); //把'\n'从缓冲区去掉
len = StackLen(bin);
printf("二进制栈的当前容量是:%d\n",len);
#if BIN2DEC
for(i = 0;i < len;i++)
{
Pop(&bin,&c);
sum += (c-48) * pow(2,i);
}
printf("转化为十进制数是:%d\n",sum);
#endif
/*******************************************************************
二进制转化为八进制:每三位二进制数组成一个八进制数,然后压入栈中,
弹出的数即为八进制数,转化为十六进制同理
*********************************************************************/
#if BIN2OCT
InitStack(&oct);
for(i = 0;i < len;i++)
{
Pop(&bin,&c);
sum = sum + (c-48) * pow(2,i%3); //每三位二进制数组成一个八进制数
if((bin.base == bin.top)||((i+1)%3 == 0))
{
c = sum + '0';
Push(&oct,c);
sum = 0;
}
}
len = StackLen(oct);
printf("八进制栈的当前容量是:%d\n",len);
printf("转化为八进制数是:");
for(i = 0;i < len;i++)
{
Pop(&oct,&c);
printf("%c",c);
}
printf("\n");
#endif
#if BIN2HEX
InitStack(&hex);
for(i = 0;i < len;i++)
{
Pop(&bin,&c);
sum = sum + (c-48) * pow(2,i%4); //每三位二进制数组成一个八进制数
if((bin.base == bin.top)||((i+1)%4 == 0))
{
c = sum + '0';
Push(&hex,c);
sum = 0;
}
}
len = StackLen(hex);
printf("十六进制栈的当前容量是:%d\n",len);
printf("转化为十六进制数是:");
for(i = 0;i < len;i++)
{
Pop(&hex,&c);
printf("%c",c);
}
printf("\n");
#endif
return 0;
}
|
|