2014-10-07

postfix with Stack


將原本的中置式子轉為後置式子,並計算結果
(10+8)-(6*5)→10 8 + 6 5 * -


#include<stdio.h>
#include<stdlib.h>
#include<math.h>

int index=-1;
void push(int);
int pop();
int stack[7]={};

int main(void){
    char data[]="10 8 + 6 5 * -";
    int times=0;
    int total=0;
    for(int i=0 ; data[i] ; i++){
          
            switch(data[i]){
                case '+':{
                     int right=pop();
                     int left=pop();
                     int temp=left+right;
                
                     push(temp);
                     break;
                     }
                case '-':{
                     int right=pop();
                     int left=pop();
                     int temp=left-right;
                    
                     push(temp);
                     break;
                     }
                case '*':{
                     int right=pop();
                     int left=pop();
                   
                     int temp=left*right;
                   
                     push(temp);
                     break;
                     }
                case '/':{
                     int right=pop();
                     int left=pop();
                     int temp=left/right;
                  
                     push(temp);
                     break;
                     }
                default:{                                         
                  if(data[i]==' ' && data[i-1]!='+' && data[i-1]!='-' && data[i-1]!='*' && data[i-1]!='/'){
                                                                         //讀到空格,如果上一個不是運算子,就把數字放入stack 
                     push(total);
                   times=0;
                   total=0;
                   }
                  else if(data[i-1]!='+' && data[i-1]!='-' && data[i-1]!='*' && data[i-1]!='/'){//為了處理多位數字元
                       if(data[i-1]!=' ')                     
                       total=total*10+data[i]-'0';
                       else 
                       total+=data[i]-'0';
                       
                       }
                     break;
                         }
                        }
                        
               
            }
            printf("%d\n",pop());
            system("pause");
 return 0;   
}
void push(int num){
     index++;
     if(index>6){
         printf("stack is full\n");
         return;
          }
     else{
       
         stack[index]=num;
         }
     }
int pop(){

        if(index-1>=-1)
           return stack[index--];

        else{
             printf("stack is empty");
             return 0;
             }
  
     
     }

沒有留言:

張貼留言

(VM) Ubuntu enable ssh

OS版本:14.04 LTS 相關指令: sudo apt-get install openssh-server Port forwarding設定 : 以virtual box為例子,網路->進階->連接阜轉送(port forwarding)