栈的例题——进制转化

用栈实现进制转化

二进制转十进制

#include 
#include 
#include 

#define OK      1
#define ERROR   0
#define STACK_INIT_SIZE 20
#define STACKINCREMENT  10

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+STACKINCREMENT)*sizeof(ElemType));
    }
    *(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()
{
     
    ElemType c;
    sqStack s;
    int len,i,sum=0;

    InitStack(&s); 

    printf("请输入一个二进制数,输入#表示结束\n");
    scanf("%c",&c);
    while(c!='#')
    {
     
        Push(&s,c);
        scanf("%c",&c);
    }
    getchar();

    len=StackLen(s);
    for(i=0;i<len;i++)
    {
     
        Pop(&s,&c);
        sum+=(c-48)*pow(2,i);
    }

    printf("转化为十进制为:%d",sum);

    return 0;
}

二进制转八进制

#include 
#include 
#include 

#define STACK_INIT_SIZE 20
#define STACKINCREMENT  10

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+STACKINCREMENT)*sizeof(ElemType));
   }
   *(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()
{
     
    sqStack s1;   // 第一个栈用来存放二进制数
    sqStack s2;   //第二个栈用来存放每三位二进制数转化成的八进制数
    ElemType c;
    int len,i,j,sum=0;
    InitStack(&s1);
    InitStack(&s2);
    printf("请输入一个二进制数:\n");
    printf("输入#表示结束输入!\n");
    scanf("%c",&c);
    while(c!='#')
    {
     
        Push(&s1,c);
        scanf("%c",&c);
    }
    getchar();
    len = StackLen(s1);
    for(i=0;i<len;i+=3)
    {
     
        for(j=0;j<3;j++)
        {
     
            Pop(&s1,&c);
            sum+=(c-48)*pow(2,j);
            if(s1.top == s1.base)
            {
     
                break;
            }
        }
        Push(&s2,sum+48);
        sum=0;
    }
    printf("转化为八进制数为:\n");
    while(s2.top != s2.base)
    {
     
        Pop(&s2,&c);
        printf("%c",c);
    }

    return 0;
}

你可能感兴趣的:(栈的例题——进制转化)