数据结构实验之栈与队列一:进制转换
Description
输入一个十进制非负整数,将其转换成对应的 R (2 <= R <= 9) 进制数,并输出。Input
第一行输入需要转换的十进制非负整数; 第二行输入 R。Output
输出转换所得的 R 进制数。Sample
Input1279
8
Output
2377
#include<bits/stdc++.h>
using namespace std;
const int MAXSIZE=100;
typedef struct node
{
int top;
int len;
int*data;
} Stack;
void push(Stack &sta,int x)//入栈
{
if(sta.top==sta.len)//判栈满
{
sta.data=(int*)realloc(sta.data,sizeof(int)*(sta.len+MAXSIZE));
sta.len=sta.len+MAXSIZE;
}
else
{
sta.data[sta.top]=x;
sta.top++;
}
}
void pop(Stack &sta)//出栈
{
if(sta.top!=0)//判栈空
{
sta.top--;
cout<<sta.data[sta.top];
}
}
bool isempty(Stack&sta)
{
if(sta.top==0)
return false;
else
return true;
}
int main()
{
int num,k;
cin>>num>>k;
Stack sta;
sta.data=(int*)malloc(sizeof(int)*MAXSIZE);
sta.top=0;
sta.len=MAXSIZE;
if(num==0)
printf("%d",num);
else
{
while(num!=0)
{
int n=num%k;
push(sta,n);
num=num/k;
}
while(isempty(sta))
{
pop(sta);
}
}
return 0;
}