使用堆栈的后进先出的原理,实现十进制转换成二进制、八进制、十六进制:
根据十进制转换其余进制的原理,对十进制取余。然后根据LIFO:4、0、5、2放进堆栈,出来的时候就是转换好的八进制的2504。
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#define STACK_SIZE 1024
typedef struct {
int *base;
int *top;
int stack_size;
}STACK;
int stack_init(STACK *s)
{
s->base = (int *)malloc(STACK_SIZE * sizeof(int));
if (s->base == NULL)
{
return -1;
}
s->top = s->base;
s->stack_size = STACK_SIZE;
return 0;
}
void stack_destroy(STACK *s)
{
free(s->base);
s->base = s->top = NULL;
s->stack_size = 0;
}
int stack_length(STACK *s)
{
int length = 0;
length = s->top - s->base;
return length;
}
int stack_empty(STACK *s)
{
if (s->top == s->base)
{
return 1;
}
else
{
return 0;
}
}
int stack_push(STACK *s, int e)
{
if (stack_length(s) >= s->stack_size)
{
return -1;
}
*(s->top) = e;
s->top++;
return 0;
}
int stack_pop(STACK *s, int *e)
{
if (stack_length(s) == 0)
{
return -1;
}
s->top--;
*e = *(s->top);
return 0;
}
int main(int argc, char *argv[])
{
STACK *s;
int n = 0, type = 0;;
int elem;
if (argc < 3)
{
printf("usage: ./conversion <2 8 16 > < num>\n");
return -1;
}
type = atoi(argv[1]);
n = atoi(argv[2]);
s = (STACK *)malloc(sizeof(STACK));
if (s == NULL)
{
return -1;
}
stack_init(s);
while(n > 0)
{
stack_push(s, n % type);
n = n / type;
}
while(stack_empty(s) == 0)
{
stack_pop(s, &elem);
printf("%d", elem);
}
putchar('\n');
return 0;
}
执行结果: