利用栈实现,将余数依次压栈再出栈。
#include <stdlib.h>
#include <stdio.h>
#define MAXSIZE 100
typedef struct
{
int data[MAXSIZE];
int top;
}seqstack,*pseqstack;
pseqstack init_stack(void)
{
pseqstack s;
s = (pseqstack)malloc(sizeof(seqstack));
if (s)
s->top = -1;
else
printf("申请失败");
return s;
}
int empty_stack(pseqstack s)
{
if (!s)
{
printf("栈不存在");
return(-1);
}
if (s->top == -1)
return(1);
else
return(0);
}
int push_stack(pseqstack s, int dat)
{
if (!s)
{
printf("栈不存在,无法入栈");
return(-1);
}
if (s->top == MAXSIZE - 1)
{
printf("栈满,无法插入");
return(0);
}
s->top++;
s->data[s->top] = dat;
return(1);
}
int pop_stack(pseqstack s, int *dat)
{
if (!s)
{
printf("栈不存在,无法出栈");
return(-1);
}
if (empty_stack(s))
{
printf("栈空,无法出栈");
return(0);
}
else
{
*dat = s->data[s->top];
s->top--;
return(1);
}
}
int get_top(pseqstack s, int *t)
{
if (!s)
{
printf("栈不存在");
return(-1);
}
if (empty_stack(s))
{
printf("栈空,无法出栈");
return(0);
}
else
{
*t = s->data[s->top];
return(1);
}
}
void destroy_stack(pseqstack *s)
{
if (*s)
free(*s);
*s = NULL;
}
void display_stack(pseqstack s)
{
if (! s)
{
printf("栈不存在");
}
else
{
for (int i = -1; i < s->top; i++)
printf("%d\n", s->data[i + 1]);
}
}
int convert(int n, int r)
{
int x;
pseqstack s = init_stack();
if (!r)
{
printf("基数为0,无法计算!");
return(-1);
}
while (n)
{
push_stack(s, n%r);
n /= r;
}
while (!empty_stack(s))//!!使用已有函数来简化
{
pop_stack(s, &x);
printf("%d", x);
}
printf("\n");
destroy_stack(&s);
}
int main()
{
convert(1023, 7);
while (true)
{
}
}