C语言实现:【问题描述】 写一个算法,将一个非负十进制数转为一个等价的八进制数 要求使用堆栈,且堆栈的基本操作使用链栈实现 【输入形式】 输入一个非负十进制整数 【输出形式】 输出对应八进制数 【样例输入】 10 【样例输出】 12
时间: 2023-11-28 12:05:14 浏览: 38
以下是使用链栈实现十进制转八进制的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
typedef struct Stack {
Node *top;
} Stack;
void initStack(Stack *s) {
s->top = NULL;
}
void push(Stack *s, int data) {
Node *node = (Node *) malloc(sizeof(Node));
node->data = data;
node->next = s->top;
s->top = node;
}
int pop(Stack *s) {
if (s->top == NULL) {
printf("Stack is empty!\n");
exit(-1);
}
Node *p = s->top;
int data = p->data;
s->top = p->next;
free(p);
return data;
}
int isEmpty(Stack *s) {
return s->top == NULL;
}
void decimalToOctal(int decimal) {
Stack s;
initStack(&s);
while (decimal > 0) {
push(&s, decimal % 8);
decimal /= 8;
}
while (!isEmpty(&s)) {
printf("%d", pop(&s));
}
}
int main() {
int decimal;
scanf("%d", &decimal);
decimalToOctal(decimal);
return 0;
}
```
首先定义了一个链栈,包含节点和栈本身两个结构体。然后实现了初始化、入栈、出栈、判断栈是否为空等基本操作。
在主函数中,先读入一个非负十进制整数,然后调用 decimalToOctal 函数进行转换。该函数将每次 decimal 取模 8 的余数入栈,直到 decimal 为 0 为止。最后弹出栈中的元素,即可得到对应的八进制数。
例如输入 10,按照算法可得到二进制数为 12,输出即为对应的八进制数。