第1題
以下是一中序運算式(Infix expression)轉換(Convert)成後序運算式 (Postfix expression)的演算法 operstk = the empty stack; while(not end of input){ symb = next input character; if(symb is an operand) add symb to the postfix string; else{ while(!empty(operstk) && precedence(stacktop(operstk),symb)){ topsymb = pop(operstk); add topsymb to the postfix string; } /*end while*/ if (empty(operstk) || symb != ‘)’) push(operstk, symb); else topsymb = pop(operstk); } /*end else*/ } /*end while*/ while(!empty(operstk)){ topsymb = pop(operstk); add topsymb to the postfix string; } /*end while*/ 其中資料結構: “operstk”:用來儲存運算子的堆疊(Stack); “stacktop(operstk)”:表示top 指標所指堆疊operstk 的運算子; 程序(Procedures)或函數(Functions): “empty(operstk)”:檢查堆疊operstk 是否為空的布林函數; “pop(operstk)”:從堆疊operstk 中取出一運算子; “push(operstk, symb)”:將運算子symb 存入堆疊operstk; “precedence(op1,op2)”:布林函數,定義在一沒有左右括弧的中序運算 式中,op1 運算子出現在op2 運算子的左邊時,當op1 運算子優先順序不 低於op2 運算子,則設定成TRUE,否則為FALSE。例如,我們給定 precedence(‘*’, ‘+’)=TRUE ,precedence(‘+’, ‘+’)=TRUE , precedence(‘+’, ‘*’)=FALSE,為了處理運算式左右括弧,設定下列 的precedence: precedence(‘(’, op) = FALSE /*op 為任一運算子*/ precedence(op, ‘(’) = FALSE /*op 為除’)’外的任一運算子*/ precedence(op, ‘)’) = TRUE /*op 為除’(’外的任一運算子*/ precedence(‘)’, op) = undefined /*op 為任一運算子*/ 以中序運算式(2+3)*4 為例,執行上述演算法,依處理每一個運算子或運 算元時,輸出postfix string 及operstk 內容為何(“eos”表示end of string)? (25 分) symbol postfix string operstk ( + ) * eos