代码采用链式栈的数据结构。
逻辑原理:
159/8=19……7;
19/8=2……3;
2/8=0……2;
计算中先得到了7,再是3和2,但为了输出八进制数237。
先得到的后输出符合栈的结构特点。
思路分析:
(1)创建一个空栈:
涉及结构体和malloc的使用;
(2)输入一个正整数:
对于有范围的输入数据一般会使用goto语句,在输入错误后,执行重新输入;
(3)将数据除以8,余数压入栈中,直至数据为0:
使用while与入栈操作即可解决;
(4)最后将栈内元素输出:
出栈操作,千万不要忘记free空出来的节点。
(5)记得把栈给销毁,养成好习惯。
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct list {
int val;
struct list* next;
}stack;
stack* creatTop() {
stack* top = (stack*)malloc(sizeof(stack));
top->next = NULL;
return top;
}
int getdata() {
int data=0;
printf("请输入一个十进制正整数:\n");
pos_1:
scanf_s("%d",&data);
if (data <= 0 || data % 1 != 0){
printf("输入错误,请重新输入。");
goto pos_1;
}
return data;
}
void pushStack(stack* top,int element) {
stack* node = (stack*)malloc(sizeof(stack));
node->val = element;
node->next = top->next;
top->next = node;
}
void eightScale(stack* top, int data) {
while (data) {
int element = data % 8;
pushStack(top, element);
data /= 8;
}
}
bool stackEmpty(stack* top) {
return top->next == NULL ? true: false;
}
void popStack(stack* top) {
printf("成功转化八进制数:");
while (top->next) {
stack* temp=top->next;
printf("%d", temp->val);
top->next = temp->next;
free(temp);
temp = NULL;
}
}
int main() {
stack* top = creatTop();
int data = getdata();
eightScale(top, data);
popStack(top);
free(top);
top = NULL;
return 0;
}
这其实是我的一道练习题,这里的出栈操作popStack,也把栈清空了。
同样可以把8换成16或者2,实现转二进制或十六进制。
有兴趣的可以研究一下负数和小数的数制转换。