数据结构之利用栈进行进制转换

测试截图:
这里写图片描述
源代码:

//测试环境:VS2015

#include "stdafx.h"
#include<stdlib.h>
#include<stdio.h>

#define STACK_INIT_SIZE 100
#define STACKCREMENT 10
#define OK 1
#define ERROR 0
#define OVERFLOW -2

typedef struct
{
    int *top;
    int *base;
    int stackSize;
}SqStack;

int initStack(SqStack &S)
{
    //建立空栈
    S.base = (int *)malloc(STACK_INIT_SIZE * sizeof(SqStack));
    S.top = S.base;
    S.stackSize = STACK_INIT_SIZE;
    return OK;
}

//释放栈
int destroyStack(SqStack &S)
{
    free(S.base);
    S.base = NULL;
    S.top = NULL;
    S.stackSize = 0;
    return OK;
}

//清空栈
int clearStack(SqStack &S)
{
    if (S.top == S.base)return OK;
    S.top = S.base;
    return OK;
}

//入栈
int push(SqStack &S, int e)
{
    if ((S.top - S.base) == S.stackSize)
    {
        S.base = (int *)realloc(S.base, (S.stackSize + STACKCREMENT) * sizeof(SqStack));
        if (!S.base)exit(OVERFLOW);
        S.top = S.base + S.stackSize;
        S.stackSize += STACKCREMENT;
    }
    *S.top++ = e;
    return OK;
}

int getTop(SqStack S, int &e)
{
    if (S.top == S.base)return ERROR;
    e = *--S.top;
    return OK;
}

int pop(SqStack &S, int &e)
{
    if (S.top == S.base)return ERROR;
    e = *--S.top;
    return OK;
}

int stackEmpty(SqStack S)
{
    return S.top == S.base;
}

int visit(int e)
{
    printf("%d ", e);
    return OK;
}

int stackTraverse(SqStack S, int(*visit)(int))
{
    if (S.top == S.base)
    {
        printf("栈中没有元素\n");
        return ERROR;
    }
    while (S.top > S.base)
    {
        visit(*S.base++);
    }
    return OK;
}

int stackLength(SqStack S)
{
    return S.top - S.base;
}


int main()
{
    //基于算法N=(N div d) * d + N % d (N是十进制数,d为其他进制数,div:整除,%:求余)
    //支持由十进制到2--10进制的转换,不支持浮点型
    SqStack S;
    initStack(S);
    printf("请输入进制:");
    int d;
    scanf_s("%d", &d);
    printf("十进制数:");
    int N;
    scanf_s("%d", &N);
    while (N)
    {
        push(S, N%d);
        N /= d;
    }
    printf("输出转换后的数:");
    while (!stackEmpty(S))
    {
        int e;
        pop(S, e);
        printf_s("%d", e);
    }
    printf("\n");
    return 0;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值