SDUTOJ - 2131 数据结构实验之栈与队列一:进制转换

本文介绍了一种使用栈数据结构实现数字进制转换的方法。通过将输入数字不断除以目标进制并取余数,然后将余数压入栈中,最后依次弹出栈中的元素即可得到转换后的数字字符串。文章提供了详细的C++代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接

#include <iostream>
#include <cstdlib>

using namespace std;

typedef int ElementType;

typedef struct Snode
{
    ElementType x;
    struct Snode * next;
} Snode, *Ptr_snode;


typedef struct Stack
{
    Snode* top;
    int length;
} Stack;

void Init(Stack &s)
{
    s.top = NULL;
    s.length = 0;
}

void Push(Stack &s, ElementType x)
{
    Ptr_snode p = (Ptr_snode) malloc( sizeof(Snode) );
    p->x = x;
    p->next = s.top;
    s.top = p;
    s.length++;
}

bool Pop(Stack &s)
{
    if(s.top)
    {
        Ptr_snode t = s.top;
        s.top = s.top->next;
        free(t);
        s.length--;
        return true;
    }
    else
    {
        return false;
    }
}

bool Top(Stack &s, ElementType &x)
{
    if(s.top)
    {
        x = s.top->x;
        return true;
    }
    else
    {
        return false;
    }
}

bool Empty(Stack &s)
{
    return s.top == NULL;
}

int main()
{
    int n, d;
    ios::sync_with_stdio(false);
    while(cin>>n>>d){
    Stack s;
    Init(s);
    if(n == 0)//向0致敬
    {
        cout<<0<<endl;
        continue;
    }
    while(n)
    {
        Push(s, n % d);
        n /= d;
    }
    while(!Empty(s))
    {
        int t;
        Top(s, t);
        cout<<t;
        Pop(s);
    }
    cout<<'\n';
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值