数据结构实验之栈一:进制转换
Time Limit: 1000MS Memory limit: 65536K
题目描述
输入一个十进制整数,将其转换成对应的R(2<=R<=9)进制数,并输出。
输入
第一行输入需要转换的十进制数;
第二行输入R。
输出
输出转换所得的R进制数。
示例输入
1279
8
示例输出
2377
Time Limit: 1000MS Memory limit: 65536K
题目描述
输入一个十进制整数,将其转换成对应的R(2<=R<=9)进制数,并输出。
输入
第一行输入需要转换的十进制数;
第二行输入R。
输出
输出转换所得的R进制数。
示例输入
1279
8
示例输出
2377
# include <stdio.h>
# include <stdlib.h>
# define STACK_INIT_SIZE 100
# define STACKINCREMENT 10
typedef int SelemType;
typedef struct{
SelemType *base;
SelemType *top;
int stacksize;
} SqStack;
void InitStack(SqStack&S);
void Push(SqStack&S,SelemType e);
void Pop(SqStack&S,SelemType&e);
/*栈空返回ture*/
bool StackEmpty(SqStack&S);
int main()
{
int N,R,e;
scanf("%d%d",&N,&R);
SqStack S;
InitStack(S);
while(N)
{
Push(S,N % R);
N = N / R;
}
while(! StackEmpty(S))
{
Pop(S,e);
printf("%d",e);
}
printf("\n");
DestroyStack(S);
return 0;
}
void InitStack(SqStack&S)
{
S.base = (SelemType*)malloc(STACK_INIT_SIZE*sizeof(SelemType));
if(!S.base)
{
exit(0);
}
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;
}
void Push(SqStack&S,SelemType e)
{
/*判断栈是否已满*/
if(S.top - S.base >= S.stacksize)
{
/*增大栈的规模*/
S.base = (SelemType*)realloc(S.base,(STACK_INIT_SIZE + STACKINCREMENT) * sizeof(SelemType));
if(!S.base)
{
exit(0);
}
/*重置S.top和S.stacksize*/
S.top = S.base + S.stacksize;
S.stacksize += STACKINCREMENT;
}
/*放入添加的元素*/
*S.top = e;
/*栈顶S.top上移*/
S.top++;
//*S.top++ = e;
}
void Pop(SqStack&S,SelemType&e)
{
/*判断栈是否为空,若为空直接返回*/
if(S.top == S.base)
return;
else
{
//e = *--S.top;
/*栈顶下移找到要Pop的元素*/
S.top--;
/*获取要出栈的元素*/
e = *S.top;
}
}
bool StackEmpty(SqStack&S)
{
if(S.top == S.base)
return true;
else
return false;
}