十进制转化为二,八,十六进制用栈实现(c语言编)

#include
#include

#define STACK_INIT_SIZE 100 /*存储空间初始分配量*/
#define STACKINCRRMENT 10 /*存储空间增量*/

#define ok        1
#define error    0
#define Status int

typedef struct
{  
    int *base; /*栈尾指针*/
    int *top; /*栈头指针*/
    int stacksize; /*当前以分配的存储空间*/
} spstack;

Status Initstack(spstack *s)
{ /*构造一个空栈s*/
    s->base = (int *)malloc(STACK_INIT_SIZE*sizeof(int));
    if (!s->base)
        exit(1); /*存储分配失败*/
    s->top = s->base;
    s->stacksize = STACK_INIT_SIZE;
    return ok;
}


int Pop(spstack *s)
{ /*若栈不空,删除栈顶元素,并用e返回其值*/
    int e;
    if(s->top==s->base)
        return error;
    e=*(--s->top);
    return e;
}


Status push(spstack *s, int e)
{ /*插入元素e为新的栈顶元素*/
    if(s->top-s->base >= s->stacksize) /*栈满,追加存储空间*/
    {
        s->base = (int*)realloc(s->base, (s->stacksize+STACKINCRRMENT)*sizeof(int));
        if (!s->base)
            exit(0);
        s->top = s->base + s->stacksize;
        s->stacksize += STACKINCRRMENT;
    }
    *s->top++=e;
    return ok;
}


void conversion(int p, int n, spstack *s)
{ /* 输入任意的十进制数转换成想换成的进制数*/
    int m;

    Initstack(s);
    do
    {
        push(s, p%n);
        p = p / n;
    } while (p);
    while (s->base != s->top)
    {
        m = Pop(s);
        if (m < 10)
            printf("%d", m);
        else
            printf("%c", m-10+'A');
    }
}

 

int main()
{
    int p, n;
    spstack s;

    printf("输入要转换成?进制:\n");
    scanf("%d", &n);
    getchar();
    printf("输入要转换的进制数:\n");
    scanf("%d", &p);
    conversion(p, n, &s);
 putchar('\n');

    return 0;
}

你可能感兴趣的:(栈)