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

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

Time Limit: 1000 ms Memory Limit: 65536 KiB

Problem Description

输入一个十进制非负整数,将其转换成对应的 R (2 <= R <= 9) 进制数,并输出。

Input

第一行输入需要转换的十进制非负整数;
第二行输入 R。

Output

输出转换所得的 R 进制数。

Sample Input

1279
8

Sample Output

2377

这题考了栈的进栈与出栈,其他的就是进制转换的模板了,由于只有2到9,还是比较简单的。

非线性

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct node//栈的节点
{
    int data;
    struct node *next;
}Node;

typedef struct stack
{
    Node *base,*top;
}Stack;

Node *newnode()//开辟一个节点
{
    Node *t;
    t = (Node *)malloc(sizeof(Node));
    t->next = NULL;
    return t;
}

Stack *Newstack()//建立一个新栈
{
    Stack *t;
    t = (Stack *)malloc(sizeof(Stack));
    t->top = newnode();
    t->base = t->top;
    return t;
}

void push(Stack *t,int x)//入栈
{
    Node *p = newnode();
    p->data = x;
    p->next = t->top->next;
    t->top->next = p;
    t->base = p;
}

int top(Stack *t)//询问栈顶元素
{
    return t->top->next->data;
}

void pop(Stack *t)//出栈
{
    Node *p;
    p = t->top->next;
    t->top->next = t->top->next->next;
    free(p);
}

void show(Stack *t)//输出栈
{
    while(t->top->next)
    {
        printf("%d",top(t));
        pop(t);
    }
    printf("\n");
}

int main()
{
    int n,r;
    scanf("%d%d",&n,&r);
    Stack *t;
    t = Newstack();
    if(n==0)
        printf("0\n");
    while(n)
    {
        push(t,n%r);
        n /= r;
    }
    show(t);
    return 0;
}

线性

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct stack
{
    int *top,*base;
    int len;
}Stack;

Stack newstack()//建立新栈
{
    Stack t;
    t.top = (int *)malloc(40*sizeof(int));
    t.base = t.top;
    t.len = 0;
    return t;
}

int top(Stack *t)//询问栈顶元素
{
    return *(t->top-1);
}

void pop(Stack *t)//出栈
{
    t->top--;
    t->len--;
}

void push(Stack *t,int x)//进栈
{
    *(t->top) = x;
    t->top++;
    t->len++;
}

int main()
{
    int x,r;
    Stack t;
    t = newstack();
    scanf("%d%d",&x,&r);
    if(x==0)
        push(&t,0);
    while(x)
    {
        push(&t,x%r);
        x /= r;
    }
    while(t.len)
    {
        printf("%d",top(&t));
        pop(&t);
    }
    printf("\n");
    return 0;
}
posted @   洛沐辰  阅读(799)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示