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

来源:互联网 发布:淘宝卖家扣分在哪里看 编辑:程序博客网 时间:2024/06/01 14:21

Problem Description

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

Input

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

Output

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

Example Input

1279
8

Example Output

2377

注意输入的数字为0

代码1

#include<stdio.h>#include<stdlib.h>typedef struct node{    int data;    struct node *next;}ST;int main(){    ST *head, *p, *tail;    int n, r;    while(~scanf("%d %d", &n, &r))    {        head = (ST *)malloc(sizeof(ST));//头结点        head->next = NULL;        tail = head;        if(n == 0) {printf("0\n"); continue;}//如果n等于0,无论r等于多少,进制转换,的结果都是0        else        {            while(n > 0)            {                p = (ST *)malloc(sizeof(ST));                p->data = n % r;//对r取余压入栈,                p->next = tail->next;//逆序建立链表,插入到头结点                tail->next = p;                n = n / r;            }        }        for(tail = head->next; tail != NULL; tail = tail->next)        {            printf("%d",tail->data);        }        printf("\n");    }    return 0;}

代码2

#include<iostream>#include<cstdlib>#define STACKSIZE 1000int n , m , e;using namespace std;typedef struct{    int *base;    int *top;    int stacksize;}SqStack;bool InitStack(SqStack &S){    S.base = (int *)malloc(STACKSIZE*sizeof(int));    if(!S.base) return false;    S.top = S.base;    S.stacksize = STACKSIZE;    return true;}bool GetTop(SqStack S,int &e){    if(S.top == S.base) return false;     e = *(S.top - 1); return true;}bool Push(SqStack &S, int e){    if(S.top - S.base >= S.stacksize)    {        S.base = (int *)malloc(STACKSIZE*sizeof(int));        if(!S.base) return false;        S.top = S.base+S.stacksize;        S.stacksize += STACKSIZE;    }    *S.top++ = e;return true;}bool Pop(SqStack &S,int &e){    if(S.top == S.base) return false;     e = *--S.top; return true;}bool StackEmpty(SqStack &S){    if(S.top == S.base) return false;    return true;}int main(){    SqStack S;    InitStack(S);    while(cin >> n >> m)    {    if(n==0) cout << n << endl;    else    {    while(n)    {        Push(S,n%m);        n /=m;    }    while(StackEmpty(S))    {       Pop(S,e);       cout << e;    }    cout << endl;    }    }    return 0;}
阅读全文
0 0
原创粉丝点击