C语言:栈实现进制间转换

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/baidu_41666198/article/details/80635542

利用栈的后进先出性质写一个10到8进制转换的小程序,数组方式实现栈,代码如下:

#include<stdio.h>
#include<stdlib.h>
#define stack_size 100
#define stack_crement_size 10
typedef int Elemtype;

///////////////////声明一个栈 
typedef struct Stack
{
     Elemtype *top;
     Elemtype *base;
     int stacksize;
}sqstack;

//函数声明
void IntiStack(sqstack *s);
int Push(sqstack* s,Elemtype e);
void Pop(sqstack* s,Elemtype *e);
int StackLen(sqstack s);
int StackEmpty(sqstack* s);
void DestoryStack(sqstack* s); 

/////////////////初始化栈 
void IntiStack(sqstack *s)
{
    s->base = (Elemtype*)malloc(sizeof(Elemtype)*stack_size);
    if(!s->base)
        exit(0);

    s->top = s->base;                 //设置栈为空 
    s->stacksize = stack_size;
}

/////////////////入栈操作 
int Push(sqstack* s,Elemtype e)
{
    if(s->top - s->base >= s->stacksize)    //判断是否栈满 
    {
        s->base = (Elemtype*)realloc(s->base,(s->stacksize + stack_crement_size)*sizeof(Elemtype));
        if(!s->base)
         exit(0);

        s->top = s->base + s->stacksize;                                   //重新设置栈顶 
        s->stacksize += stack_crement_size;                                //重新设置栈的大小 
    }

    *(s->top) = e;
    s->top++;

    return 1;
}

/////////////////出栈操作 
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 StackEmpty(sqstack* s)
{
    return (s->stacksize == 0);
}
/////////////////销毁栈 
void DestoryStack(sqstack* s)
{
    int i,len;
    len = s->stacksize;

    for( i = 0; i <len; i++)
    {
        s->base++;
        free(s->base);
    }

    s->base = s->top = NULL;
    s->stacksize  = 0;
}

int main(void)
{
    sqstack s;
    int i,c,k;
    int j = 0;               //用来记录转化后的8进制数位数 
    int N;
    printf("请输入一个十进制数:");
    scanf("%d",&N); 
    int W = N; 

    IntiStack(&s);           //初始化栈 

      while(N != 0)          //除k取余法转换,并把余数入栈
    {
      k = N%8;
      Push(&s,k);
      N = N/8;
      j++;
    }


    printf("十进制数 %d 转化为八进制数为: ",W);
    for( i=0; i<j; i++)
    {
        Pop(&s,&c);
        printf("%d ",c);
    }

    //DestoryStack(&s);
    printf("\n");
    return 0;
}

展开阅读全文

没有更多推荐了,返回首页