栈、进制转化

第六周

要求:十进制转化为二进制和十六进制。用链栈存储数据

函数:

Status InitStack(LinkStack &S) //初始化

Status Push(LinkStack &S, SElemType e) //计算结果入栈

Status Pop(LinkStack &S, SElemType &e)//计算结果

int StackEmpty(LinkStack S) //判断栈S是否为空

Status DtoB(int N) //转化为二进制

Status DtoH(int N) //转化为十六进制

先定义结构类型为链栈

初始化栈

Status InitStack(LinkStack &S)
{
    S = NULL;
    return OK;
}

入栈函数

Status Push(LinkStack &S, SElemType e)
{
    LinkStack p;
    p = new StackNode;
    if (!p) {
        return OVERFLOW;
    }
    p->data = e;
    p->next = S;
    S = p;
    return OK;
}

出栈函数

Status Pop(LinkStack &S, SElemType &e)
{
    LinkStack p;
    if (!S)
        return ERROR;
    e = S->data;
    p = S;
    S = S->next;
    delete p;
    return OK;
}

判断栈是否为空

int StackEmpty(LinkStack S)
{
    if (!S)
        return 1;
    else
        return 0;
}

转化为二进制函数

Status DtoB(int N)
{
    LinkStack S;
    SElemType e;
    InitStack(S);
    while (N) {
        Push(S, N % 2);
        N = N / 2;
    }
    while (!StackEmpty(S))
    {
        Pop(S, e);
        cout << e;
    }
    return OK;
}

转化为十六进制

Status DtoH(int N)
{
    LinkStack S;
    SElemType e;
    char H[] = "0123456789ABCDEF";
    InitStack(S);
    while (N) {
        Push(S, N % 16);
        N = N / 16;
    }
    while (!StackEmpty(S)) 
    {
        Pop(S, e);
        cout << H[e]; 
    }
    return OK;
}

测试函数

int main()
{
    int N;
    cout << "请输入一个非负的十进制整数:";
    cin >> N;
    cout << "对应的二进制数为:";
    DtoB(N);
    cout << "
";
    cout << "对应的十六进制数为:";
    DtoH(N);
}

运行结果

原文地址:https://www.cnblogs.com/cjwen/p/10654067.html