後綴表達式求值

 

  1. #include<stdio.h> 
  2. #include<string.h> 
  3. #include<ctype.h> 
  4. #include<stdlib.h> 
  5. #define MAXSIZE 30 
  6.   
  7. typedef int ElemType; 
  8. typedef struct Stack{//棧結構  
  9.     ElemType data[MAXSIZE]; 
  10.     int top;//棧頂指針  
  11. }Stack,*pStack; 
  12.   
  13. void initStack(pStack S){//初始化棧  
  14.     S->top = -1; 
  15. bool push(pStack S,ElemType e){  
  16.     if(S->top == MAXSIZE-1){ 
  17.         puts("棧滿"); 
  18.         return false
  19.     } 
  20.     S->data[++(S->top)] = e; 
  21.     return true
  22. bool pop(pStack S,ElemType *e){ 
  23.     if(S->top == -1){ 
  24.         puts("棧空"); 
  25.         return false
  26.     } 
  27.     *e = S->data[(S->top)--]; 
  28.     return true
  29. int main(void){ 
  30.     char string[MAXSIZE];//存儲字符串  
  31.     char tempNumber[MAXSIZE];//存儲數值字符  
  32.     char ch;//分解每個字符  
  33.     int index; 
  34.     int number;//從字符中獲得的數值  
  35.     int result = 0;//最終結果  
  36.     int count = 0;//數字計數  
  37.     int a1,a2;//輔助數值計算  
  38.     bool tag;//標誌位,數字是否已經結束  
  39.     Stack numberStack;//數字棧  
  40.     pStack S = &numberStack;//指向棧的指針  
  41.      
  42.     initStack(S);//初始化棧  
  43.     puts("Enter a string"); 
  44.     gets(string); 
  45.     for(index=0;index<strlen(string);index++){ 
  46.         ch = string[index]; 
  47.         if(isdigit(ch)){ 
  48.             tag = true;//現在輸入的是數字  
  49.             tempNumber[count] = ch; 
  50.             count++; 
  51.         } 
  52.         else
  53.             if(tag){//判斷上一個字符是不是數值  
  54.                 tempNumber[count] = '\0';//一個數值結束了  
  55.                 number = atoi(tempNumber); 
  56.                 push(S,number); 
  57.                 count = 0;//重新計算數值  
  58.                 tag = false
  59.             } 
  60.             switch(ch){ 
  61.                 case '+'
  62.                      pop(S,&a2); 
  63.                      pop(S,&a1); 
  64.                      push(S,a1+a2); 
  65.                      break
  66.                 case '-'
  67.                      pop(S,&a2); 
  68.                      pop(S,&a1); 
  69.                      push(S,a1-a2); 
  70.                      break
  71.                 case '*'
  72.                      pop(S,&a2); 
  73.                      pop(S,&a1); 
  74.                      push(S,a1*a2); 
  75.                      break
  76.                 case '/'
  77.                      pop(S,&a2); 
  78.                      pop(S,&a1); 
  79.                      push(S,a1/a2); 
  80.                      break
  81.                 default
  82.                      break
  83.             } 
  84.         } 
  85.     } 
  86.     pop(S,&result); 
  87.     printf("%d",result); 
  88.     getchar(); 
  89.     return 0; 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章