算術表達式(中綴表達式)轉換為後綴表達式
阿新 • • 發佈:2018-07-28
typedef 一次 代碼 fin efault stdio.h 所有 include 得到
將後綴表達式exp轉換為postexp的過程如下:
while(從exp讀取字符ch,ch!=‘\0‘)
{
若ch為數字,將後繼的數字都一次存放到postexp中,並以字符‘#‘標誌數值串的結束;
若ch為左括號“(”,將此括號進棧到運算符棧op中;
若ch為右括號“)”,將運算符棧op依次出棧,直到“(”,並將“(”也出棧;
若ch為運算符,優先級不大於運算符op的棧頂運算符(除棧頂運算符為“(”外)的優先級,則依次出棧並存入到postexp中,然後將ch進棧
}
若中綴表達式exp掃描完畢,將運算符棧op中的所有運算符依次出棧並存放到postexp中,就得到了後綴表達式。
完整代碼:
#include <stdio.h> #define MAXSIZE 50 typedef char elemType; //運算符棧 typedef struct{ elemType data[MAXSIZE]; int top; }OP; OP op; //中綴表達式轉為後綴表達式 void trans(char exp[],char postexp[]){ op.top=-1; int i=0,j=0; char ch=exp[i]; while(ch!=‘\0‘){ switch(ch){case ‘(‘:{ op.top++; op.data[op.top] = ch; break; } case ‘)‘:{ while(op.data[op.top]!=‘(‘){ postexp[j++]=op.data[op.top--]; } op.top--; //去除 ‘(‘ break; } case ‘+‘: case ‘-‘:{ while(op.top!=-1&&op.data[op.top]!=‘(‘){ postexp[j++]=op.data[op.top--]; } op.top++; op.data[op.top]=ch; break; } case ‘*‘: case ‘/‘:{ while(op.top!=-1&&(op.data[op.top]==‘*‘||op.data[op.top]==‘/‘)){ postexp[j++]=op.data[op.top]; op.top--; } op.top++; op.data[op.top]=ch; break; } case ‘ ‘:break; default :{ while(ch>=‘0‘&&ch<=‘9‘){ postexp[j++]=ch; i++; ch=exp[i]; } i--; //不是數字 退後一個,用switch來進行判斷 postexp[j++]=‘#‘; //在數字結束後添加‘#‘以便區分 } } i++; ch=exp[i]; } while(op.top!=-1){ //將運算符棧中 postexp[j++]=op.data[op.top--]; } postexp[j]=‘\0‘; }
算術表達式(中綴表達式)轉換為後綴表達式