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

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

Description

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

Input

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

Output

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

Sample

Input 

1279
8

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("
");
}

int main()
{
    int n,r;
    scanf("%d%d",&n,&r);
    Stack *t;
    t = Newstack();
    if(n==0)
        printf("0
");
    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("
");
    return 0;
}
原文地址:https://www.cnblogs.com/xiaolitongxueyaoshangjin/p/12651592.html