数据结构c语言版怎么实现十进制数转换成二进制数(要求用栈)
这是比较简单的一个小程序,使用了自定义的链表堆栈。考虑到程序不会长期执行,程序在退出时操作系统会自动清理这个程序的私有虚拟内存空间,所以就没有设计清理功能(尽管也很简单)。下面是程序截图: 下面就是程序代码,已经加入了简单的注释信息。 希望可以帮到你! ----------------------------------binary_convert。c---------------------------------- // 为了使用printf()、scanf()和perror()函数 #include // 为了使用malloc()、free()和exit()函数 #include...全部
这是比较简单的一个小程序,使用了自定义的链表堆栈。考虑到程序不会长期执行,程序在退出时操作系统会自动清理这个程序的私有虚拟内存空间,所以就没有设计清理功能(尽管也很简单)。下面是程序截图: 下面就是程序代码,已经加入了简单的注释信息。
希望可以帮到你! ----------------------------------binary_convert。c---------------------------------- // 为了使用printf()、scanf()和perror()函数 #include // 为了使用malloc()、free()和exit()函数 #include typedef struct node *frame; // 栈帧的数据结构 struct node { ? ?int data; ? ?frame prev; }; // 堆栈长度 static int len = 0; // 堆栈的顶部 static frame top = NULL; // 获得堆栈的栈帧数量(长度) static int getlen(void) { ? ?return len; } // 判断堆栈是否为空 static int is_empty(void) { ? ?return (0 == len); } // 产生一个新的栈帧 static frame new_frame(int data) { ? ?frame nf = (frame) malloc(sizeof(struct node)); ? ?// 下面3句是在没有分配到动态内存时做的错误处理 ? ?if (NULL == nf) { ? ? ? ?perror("Error: can not allocate memory, quit。
"); ? ? ? ?exit(0); ? ?} ? ?nf->data = data; ? ?nf->prev = NULL; ? ?return nf; } // 出栈操作 static int pop(void) { ? ?if (!is_empty()) { ? ? ? ?int ret_int = top->data; ? ? ? ?frame out = top; ? ? ? ?top = top->prev; ? ? ? ?len--; ? ? ? ?free(out); ? ? ? ?return ret_int; ? ?} else { ? ? ? ?perror("Error: can not pop from stack, because the stack is empty。
"); ? ? ? ?exit(0); ? ?} } // 入栈操作 static void push(int data) { ? ?frame in = new_frame(data); ? ?in->prev = top; ? ?top = in; ? ?len ; } // 将十进制数字的余数存储到堆栈之中 void binary_convert(int num) { ? ?while(num / 2) { ? ? ? ?push(num % 2); ? ? ? ?num /= 2; ? ?} ? ?push(num % 2); } // 利用堆栈打印二进制数字 void print_binary(void) { ? ?while(!is_empty()) ? ? ? ?printf("%d", pop()); } int main(void) { ? ?// 用于接收用户输入的十进制数字 ? ?int user_in = 0; ? ?printf("Please input a positive decimal integer: "); ? ?scanf("%d", &user_in); ? ?// 将十进制数字通过堆栈转换为二进制数字 ? ?binary_convert(user_in); ? ?printf("Binary number: "); ? ?// 打印二进制数字 ? ?print_binary(); ? ?printf("
"); ? ?return 0; }。
收起