栈的应用之二进制转换为十进制,八进制和十六进制

来源:互联网 发布:淘宝怎么买高仿包包 编辑:程序博客网 时间:2024/05/07 10:02
#include<stdio.h>#include<stdlib.h>#include<math.h>#define INIT_STACK_SZIE 20#define STACK_INCREMENT 10#define OK 1#define ERROR 0typedef char Elemtype;typedef int Status;typedef struct SuqStack{Elemtype* base;Elemtype* top;int stackSize;}SuqStack;Status InitStack(SuqStack *s){s->base = (Elemtype*)malloc(sizeof(Elemtype) * INIT_STACK_SZIE);if(!s->base)return ERROR;s->top = s->base;s->stackSize = INIT_STACK_SZIE;return OK;}Status Pop(SuqStack *s,Elemtype *result){if(s->base == s->top)return ERROR;*result = *(--(s->top));return OK;}Status Push(SuqStack *s,Elemtype value){if(s->top - s->base == s->stackSize){s->base = (Elemtype*)realloc(s->base,sizeof(Elemtype) * (STACK_INCREMENT + INIT_STACK_SZIE));if(!s->base)return ERROR;s->top = s->base + INIT_STACK_SZIE;s->stackSize = INIT_STACK_SZIE + STACK_INCREMENT;}*(s->top) = value;s->top++;return OK;}int StackLength(SuqStack s){return s.top - s.base;}Status Binary2Decimal(){SuqStack s;InitStack(&s);Elemtype c;int i;int sum = 0;int len;printf("please enter binary number end of '#': ");scanf("%c",&c);while(c != '#'){Push(&s,c);scanf("%c",&c);}getchar();len = StackLength(s);for(i = 0; i < len; i++){Pop(&s,&c);sum = sum + (c-48) * pow(2,i);}printf("result is %d(10)\n",sum);return OK;}Status Binary2Octal(){Elemtype c;SuqStack s1;SuqStack s2;InitStack(&s1);InitStack(&s2);int i,j,k,len,len1,sum;printf("please enter binary number end of '#': ");scanf("%c",&c);while(c != '#'){Push(&s1,c);scanf("%c",&c);}getchar();len = StackLength(s1);for(i = 0; i < len; i = i + 3){sum = 0;for(j = 0,k = i; j < 3 && k < len; j++,k++){Pop(&s1,&c);sum = sum + (c-48) * pow(2,j); /* 1的ASCII=49  0的ASCII=48*/}//printf("%c\n",sum+48);Push(&s2,sum + 48);//sum+48为ASCII码值//栈中的元素的类型char}len1 = StackLength(s2);printf("the result is ");for(i = 0;i < len1; i++){Pop(&s2,&c);printf("%c",c);}printf("(8)\n");return OK;}Status Binary2Hexadecimal(){Elemtype c;SuqStack s1;SuqStack s2;InitStack(&s1);InitStack(&s2);int i,j,k,len,sum,len1;printf("please enter binary number end of '#': ");scanf("%c",&c);while(c != '#'){Push(&s1,c);scanf("%c",&c);}getchar();len = StackLength(s1);for(i = 0; i < len; i = i + 4){sum = 0;for(j = 0,k = i; j < 4 && k < len; j++, k++){Pop(&s1,&c);sum  = sum + (c - 48) * pow(2, j);}/* 0-------48         1-------49 * 2-------50         3-------51 * 4-------52      5-------53 * 6-------54         7-------55 * 8-------56         9-------57 * A-------65         B-------66 * C-------67         D-------68 * */if(sum < 10)Push(&s2,sum + 48);elsePush(&s2,sum + 55);}len1 = StackLength(s2);for(i = 0; i < len1; i++){Pop(&s2,&c);printf("%c",c);}printf("\n");}int main(){//Binary2Decimal();//Binary2Octal();Binary2Hexadecimal();return 0;}

0 0
原创粉丝点击