中綴表達式,形如1+2,是咱們經常使用的運算表達式,做爲天然語言被普遍的使用,可是,在計算機的計算機制中,並非直接的對這個表達式進行計算,計算有特殊的數據結構對運算表達式進行儲存和計算,就是數據結構中經常使用的堆棧,而其中有一個步驟相當重要,就是將中綴表達式轉換爲後綴表達式。ios
衆所周知,經常使用的運算符號有+、-、*、/、(、),可是這些符號在計算的時候有不一樣的優先級,乘法和除法的優先級高於加法和減法,可是遇到括號內存在表達式的狀況,那麼就要首先計算括號中的表達式。這就表明,咱們在設計程序的時候應當考量這些符號的優先級問題。express
在同一級的符號運算中,中綴表達式生成後綴表達式是很簡單的。數據結構
好比1+2-3,首先輸出1,將+彈入堆棧,而後輸出2,減號彈入堆棧,最後輸出3,到了末尾,將堆棧元素所有彈出。函數
那麼就是123-+.在這個表達式轉換中,2和3是後來輸出的元素,那麼就要匹配後來出現的運算符號,因此運算符的儲存數據結構應該知足後入先出的特色,所以咱們選用堆棧做爲儲存符號的數據結構。spa
可是在1*2+3式子中,採用剛纔的同級方式,就不合理了,他會變成123+*,意思變成先2+3再進行乘法,和原來式子表達的意思不符合,那麼就要引入優先級。設計
在這個式子中,乘法的優先級高於加法,因此當遍歷到加法的時候,乘法的優先級較高,因此應當直接就彈出乘法,再放入加法,也就是12*而後輸出3彈出乘法,也就是12*3+,符合要求。code
當式子出現括號時,好比(1+2)*3,應當先計算加法而後計算乘法,左括號直接放入堆棧,當遍歷到右括號時,彈出括號內的表達式,因此就是12+3*符合要求。blog
/************************Stack.h**********************/ #include <iostream> using namespace std; typedef char ElementType; struct Node { ElementType ch; int m; }; #define TRUE 1 #define FALSE 0 #define MAXSIZE 100 class Stack { private: Node data[MAXSIZE]; int top; public: Stack(); //構造 ~Stack(); //析構 void Add(ElementType data); //添加元素 void Pop(); //彈出元素 bool is_empty(); //判斷是否爲空 bool is_full(); //判斷是否滿 void Fix_Change(ElementType A[],int N); //輸出後綴表達式 };
/********************Stack.cpp*******************/ #include <iostream> #include "Stack.h" using namespace std; Stack::Stack() //構造函數 { top=-1; } Stack::~Stack() //析構函數 {} bool Stack::is_empty() { if (top==-1) return TRUE; else return FALSE; } bool Stack::is_full() //判斷是否滿 { if (top==MAXSIZE-1) return TRUE; else return FALSE; } void Stack::Add(ElementType da) //添加 { if (is_full()) { cout<<"ERROR!"<<endl; return; } else { data[++top].ch=da; return; } } void Stack::Pop() //彈出 { if (is_empty()) { cout<<"ERROR!"<<endl; return; } else { cout<<data[top--].ch; return; } } void Stack::Fix_Change(ElementType A[],int N) { int i=0; int m; for (i=0;i<N;i++) { if (A[i]<='9'&&A[i]>='0') cout<<A[i]; else { if (A[i]=='(') //前括號直接進入 { Add(A[i]); data[top].m=3; } else if (A[i]==')') //後括號不放入,彈出 { while (data[top].ch!='(') Pop(); top--; } else if (A[i]=='*'||A[i]=='/') //乘法和除法 { if (top==-1) { Add(A[i]); data[top].m=1; } else { m=1; if (m>data[top].m) while (top!=-1&&data[top].ch!='(') //清空棧至括號操做 Pop(); Add(A[i]); data[top].m=m; } } else if (A[i]=='+'||A[i]=='-') //加法和減法 { if (top==-1) { Add(A[i]); data[top].m=2; } else { m=2; if (m>data[top].m) while (top!=-1&&data[top].ch!='(') Pop(); Add(A[i]); data[top].m=m; } } else cout<<"ERROR!"<<endl; } if (i==N-1) { while (top!=-1) Pop(); } } }
/*********************main.cpp**********************/ #include <iostream> #include "Stack.h" using namespace std; int main() { int n; int i; ElementType *p; Stack sk; cout<<"Please enter the number of characters:"<<endl; cin>>n; p=new ElementType[n]; cout<<"Please enter the elements of the expressions:"<<endl; for (i=0;i<n;i++) cin>>p[i]; sk.Fix_Change(p,n); return 0; }