十进制转化为二进制(栈算法)
输入一个十进制数转化为二进制输出
算法:先将十进制数一直取余,对应的倒序输出则为二进制数,栈的出栈的规则为先进后出,故满足倒序输出
代码:
1 #include "stdafx.h" 2 3 #include<stdlib.h> 4 5 #include<malloc.h> 6 7 8 9 #define STACK_SIZE 100 10 11 #define STACKINCREAMENT 10 12 13 #define ERROR 0 14 15 #define OK 1 16 17 #define OVERFLOW -2 18 19 20 21 typedef int SElemType; 22 23 typedef int Status; 24 25 typedef int CElemType; 26 27 28 29 //定义栈结构体 30 31 typedef struct Stack{ 32 33 SElemType *base; 34 35 SElemType *top; 36 37 int stacksize; 38 39 }SqStack; 40 41 42 43 //函数声明 44 45 Status InitStack(SqStack &S); 46 47 CElemType Push(SqStack &S, int e); 48 49 CElemType PrintfStack(SqStack S); 50 51 CElemType PopStack(SqStack &S); 52 53 Status StackLength(SqStack S); 54 55 56 57 int main() 58 59 { 60 61 SqStack S; 62 63 InitStack(S); 64 65 int i, e, n, a; 66 67 printf("请输入需要转化的十进制数:"); 68 69 scanf_s("%d", &a); 70 71 i = a; 72 73 while (a >= 1) 74 75 { 76 77 e = a % 2; 78 79 Push(S, e); 80 81 a /= 2; 82 83 } 84 85 printf("%d转化为二进制为:", i); 86 87 PrintfStack(S); 88 89 } 90 91 92 93 //构建新的空栈 94 95 Status InitStack(SqStack &S) 96 97 { 98 99 S.base = (SElemType*)malloc(STACK_SIZE*sizeof(SElemType)); 100 101 if (!S.base) 102 103 return ERROR; 104 105 S.top = S.base; 106 107 S.stacksize = STACK_SIZE; 108 109 return OK; 110 111 } 112 113 114 115 //入栈操作 116 117 CElemType Push(SqStack &S, int e) 118 119 { 120 121 SElemType *p; 122 123 if (S.top - S.base >= S.stacksize) 124 125 { 126 127 S.base = (SElemType*)realloc(S.base, (STACK_SIZE + STACKINCREAMENT)*sizeof(SElemType)); 128 129 if (!S.base) 130 131 exit(OVERFLOW); 132 133 p = S.base; 134 135 S.top = S.base + S.stacksize; 136 137 S.stacksize += STACKINCREAMENT; 138 139 } 140 141 *S.top++ = e; 142 143 return OK; 144 145 } 146 147 148 149 //出栈操作 150 151 CElemType PopStack(SqStack &S) 152 153 { 154 155 if (S.base == S.top) 156 157 { 158 159 printf("The Stack is Empty!!!\n"); 160 161 return OK; 162 163 } 164 165 printf("出栈的元素为%d\n", *(S.top - 1)); 166 167 *(--S.top) = NULL; 168 169 }