据课本的定义,实现顺便栈的定义和相关函数的实现 在主函数中输入一个整数n,转化为m进制数,利用栈的先进后出原理,来实现余数的组合。
时间: 2023-05-19 18:01:26 浏览: 37
好的,这是一个关于栈的编程问题。以下是实现顺便栈的定义和相关函数的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define STACK_INIT_SIZE 100
#define STACK_INCREMENT 10
typedef struct {
int *base;
int *top;
int stack_size;
} SqStack;
int InitStack(SqStack *S) {
S->base = (int *)malloc(STACK_INIT_SIZE * sizeof(int));
if (!S->base) {
exit(0);
}
S->top = S->base;
S->stack_size = STACK_INIT_SIZE;
return 1;
}
int Push(SqStack *S, int e) {
if (S->top - S->base >= S->stack_size) {
S->base = (int *)realloc(S->base, (S->stack_size + STACK_INCREMENT) * sizeof(int));
if (!S->base) {
exit(0);
}
S->top = S->base + S->stack_size;
S->stack_size += STACK_INCREMENT;
}
*(S->top) = e;
S->top++;
return 1;
}
int Pop(SqStack *S, int *e) {
if (S->top == S->base) {
return 0;
}
S->top--;
*e = *(S->top);
return 1;
}
int main() {
int n, m;
SqStack S;
InitStack(&S);
printf("请输入一个整数n:");
scanf("%d", &n);
printf("请输入一个进制m:");
scanf("%d", &m);
while (n) {
Push(&S, n % m);
n /= m;
}
printf("转化为%d进制数为:", m);
while (S.top != S.base) {
int e;
Pop(&S, &e);
printf("%d", e);
}
printf("\n");
return 0;
}
```
这段代码实现了一个顺序栈,并且利用栈的先进后出原理,将一个整数n转化为m进制数。