数据结构实验之栈与队列一:进制转换
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
Hint
Source
别人的代码 链栈
#include <stdio.h>
#include <stdlib.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10//存储空间分配增量;
typedef int ElemType;
typedef struct
{
ElemType *base;
ElemType *top;
int stacksize;
}SqStack;
int InitStack(SqStack &S)
{
S.base = (ElemType *)malloc(STACK_INIT_SIZE*sizeof(ElemType));
if(!S.base)exit(-1);
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;
return 1;
}
int Push(SqStack &S,ElemType e)
{
if(S.top-S.base >= S.stacksize)
{
S.base=(ElemType *)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(ElemType));
if(!S.base) exit(-1);//分配失败;
S.top=S.base+S.stacksize;
S.stacksize+=STACKINCREMENT;
}
*S.top++ = e;
return 1;
}
int Pop(SqStack &S,ElemType &e)
{
if(S.top == S.base)return 0;
e=*--S.top;
return 1;
}
int StackEmpty(SqStack &S)
{
if(S.top==S.base) return 0;
else return 1;
}
int main()
{
int num,ss,e;
while(~scanf("%d %d",&num,&ss))
{
SqStack S;
InitStack(S);
/* if(num < 0)
printf("-"), num = -num; 这一段一开始没加,错了,后来看别人的代码发现了这个..
if(num == 0)
printf("0");*/
while(num)
{
Push(S,num%ss);
num/=ss;
}
while(StackEmpty(S))
{
Pop(S,e);
printf("%d",e);
}
}
}
编译错误......太真实了
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef int status;
#define MAXSIZE 100
typedef struct
{
ElemType *base;
ElemType *top;
int stacksize;
}Sqstack;
status IsEmpty(Sqstack &S)
{
if(S.top == S.base)return 1;
else return 0;
}
void InitStack(Sqstack &S)
{
S.base = (ElemType *)malloc(MAXSIZE * sizeof(ElemType));
S.top = S.base;
S.stacksize = MAXSIZE;
}
void push(Sqstack &S,ElemType e)
{
if(S.base -S.top >= S.stacksize)
{
S.base = (ElemType *)realloc(S.base,(50+S.stacksize)*sizeof(ElemType));
S.top =S.base +S.stacksize;
S.stacksize += 50;
}
else
{
*S.top++= e;
}
}
int Pop(Sqstack &S,ElemType &e)
{
return e = *--S.top;
}
int main()
{
int n, r;
Sqstack S;
InitStack(S);
scanf("%d %d",&n,&r);
if(n < 0)
printf("-"), n = -n;
if(n == 0)
printf("0");
while(n)
{
int cnt = n % r;
n = n /r;
push(S,cnt);
}
while(!IsEmpty(S))
{
int cnt = Pop(S,cnt);
printf("%d",cnt);
}
printf("\n");
return 0;
}
上面第一段代码一直不对可能是因为这个,加上后就对了
if(n < 0)
printf("-"), n = -n;
if(n == 0)
printf("0");
还有为啥这个要用c++才能编译出来....