【数据结构】利用栈实现进制转换

#include<bits/stdc++.h>
#include <iostream>
//#include <cstring>
//#pragma GCC optimize(2)
#include<time.h>
#include <queue>
#include <stack>
#include <cmath>
using namespace std;
#define maxn 1005
#define inf 1e18
#define eps 0.00001
typedef long long ll;
const ll mod = 1e9+7;
const double pi = acos(-1);

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

int InitStack(SqStack &S)
{
    S.base = new int[maxn];
    if(!S.base)
        exit(0);
    S.top = S.base;
    S.stacksize = maxn;
    return 1;
}

int Push(SqStack &S,int e)
{
    if(S.top-S.base == S.stacksize)
        return 0;
    *S.top++=e;
    return 1;
}

int Pop(SqStack &S,int &e)
{
    if(S.top == S.base)
        return 0;

    e = *--S.top;
    return 1;
}

int GetTop(SqStack S)
{
    if(S.top != S.base)
        return *(S.top-1);
}

void conversion(int N,int k)
{
    SqStack S;
    InitStack(S);

    cout << "将" << N << "转为" << k << "进制后的结果为:" ;

    while(N)
    {
        Push(S,N%k);
        N=N/k;
    }

    while( S.top != S.base )
    {
        int e;
        Pop(S,e);
        cout << e;
    }
    cout << endl;

}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);cout.tie(0);

    //freopen("D:\\test1.in","w",stdout);
    //srand((int)time(0));

    cout << "请输入将要转为K进制的数N以及K" << endl;

    int num,k;

    cin >> num >> k;

    conversion(num,k);

    return 0;
}

猜你喜欢

转载自blog.csdn.net/Whyckck/article/details/83904467