데이터 구조 재 미 있 는 문제 - 이 진/8 진 변환

11567 단어 데이터 구조
   1: #include <stdio.h>
   2: #include <math.h>
   3: #include <stdlib.h>
   4: #define STACK_INIT_SIZE 20
   5: #define STACKINCREMENT 10
   6:  
   7: typedef  char ElemType;
   8: typedef struct {
   9:     ElemType *base;
  10:     ElemType *top;
  11:     int stacksize;
  12: } sqStack;
  13:  
  14: void initStack(sqStack *s)
  15: {
  16:     /*                ,      s->base*/
  17:     s->base = (ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
  18:  
  19:     if(!s->base) exit(0);     /*      */
  20:  
  21:     s->top = s->base;       /*   ,      */
  22:     s->stacksize = STACK_INIT_SIZE;   /*     STACK_INIT_SIZE */
  23: }
  24:  
  25: void Push(sqStack *s, ElemType e) {
  26:     if(s->top - s->base >= s->stacksize) {
  27:         /*  ,    */
  28:         s->base = (ElemType *)realloc(s->base, (s->stacksize +
  29:                                                 STACKINCREMENT) * sizeof(ElemType));
  30:  
  31:         if(!s->base) exit(0);   /*      */
  32:  
  33:         s->top = s->base + s->stacksize;
  34:         s->stacksize = s->stacksize + STACKINCREMENT; /*        */
  35:     }
  36:  
  37:     *(s->top) = e;  /*    */
  38:     s->top++;
  39: }
  40:  
  41: void Pop(sqStack *s , ElemType *e) {
  42:     if(s->top == s->base) return;
  43:  
  44:     *e = *--(s->top);
  45: }
  46:  
  47: int StackLen(sqStack s) {
  48:     return (s.top - s.base) ;
  49: }
  50:  
  51: int main()
  52: {
  53:     ElemType c;
  54:     sqStack s1;
  55:     sqStack s2;
  56:     int len, i, j, sum = 0;
  57:     initStack(&s1);  /*     s1,          */
  58:  
  59:     printf("Please input a binary number and type '#' for end
"
);
  60:     /*  0/1         , #  */
  61:     scanf("%c", &c);
  62:  
  63:     while(c != '#')
  64:     {
  65:         if(c == '0' || c == '1')
  66:             Push(&s1, c);
  67:  
  68:         scanf("%c", &c);
  69:     }
  70:  
  71:     initStack(&s2);  /*     s2,          */
  72:     len = StackLen(s1);  /*         ,        */
  73:  
  74:     for(i = 0; i < len; i = i + 3) {
  75:         for(j = 0; j < 3; j++) {
  76:             Pop(&s1, &c); /*      */
  77:             sum = sum + (c - 48) * pow(2, j); /*       */
  78:  
  79:             if(s1.base == s1.top) break;
  80:         }
  81:  
  82:         Push(&s2, sum + 48) ; /*              */
  83:         sum = 0;
  84:  
  85:     }
  86:  
  87:     printf("The Octal from is 
"
) ;
  88:  
  89:     while(s2.base != s2.top ) { /*         */
  90:         Pop(&s2, &c);
  91:         printf("%c", c);
  92:     }
  93: }

좋은 웹페이지 즐겨찾기