利用栈实现十进制向二进制的转换c语言
时间: 2023-05-30 19:03:47 浏览: 127
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STACK_INIT_SIZE 100
#define STACK_INCREMENT 10
typedef struct {
int* base;
int* top;
int stackSize;
} Stack;
void InitStack(Stack* s) {
s->base = (int*)malloc(STACK_INIT_SIZE * sizeof(int));
if (!s->base) {
exit(1);
}
s->top = s->base;
s->stackSize = STACK_INIT_SIZE;
}
void Push(Stack* s, int e) {
if (s->top - s->base >= s->stackSize) {
s->base = (int*)realloc(s->base, (s->stackSize + STACK_INCREMENT) * sizeof(int));
if (!s->base) {
exit(1);
}
s->top = s->base + s->stackSize;
s->stackSize += STACK_INCREMENT;
}
*(s->top) = e;
s->top++;
}
void Pop(Stack* s, int* e) {
if (s->top == s->base) {
return;
}
s->top--;
*e = *(s->top);
}
int StackEmpty(Stack* s) {
return s->top == s->base;
}
void Conversion(int n, Stack* s) {
while (n) {
Push(s, n % 2);
n /= 2;
}
}
void PrintStack(Stack* s) {
int e;
while (!StackEmpty(s)) {
Pop(s, &e);
printf("%d", e);
}
}
int main() {
int n;
Stack s;
InitStack(&s);
printf("Please input a decimal integer: ");
scanf("%d", &n);
printf("The binary representation is: ");
Conversion(n, &s);
PrintStack(&s);
printf("\n");
return 0;
}
阅读全文