1. 程式人生 > >中綴表達式轉換成為後綴表達式

中綴表達式轉換成為後綴表達式

default [] 筆記 標準庫 c++ AR lib 直接 AI

算法的基本流程

遍歷中綴表達式中的數字和符號

對於數字:直接輸出

對於符號:

左括號:進棧

運算符號:與棧頂符號進行優先級比較

若棧頂符號優先級低:此符合進棧 (默認棧頂若是左括號,左括號優先級最低)

若棧頂符號優先級不低:將棧頂符號彈出並輸出,之後進棧

右括號:將棧頂符號彈出並輸出,直到匹配左括號

遍歷結束:將棧中的所有符號彈出並輸出。

下面的代碼是用之前的linkStack來實現的,沒有借助於C++標準庫,當然用C++標準庫實現起來hi更優雅一點,筆記自己用C寫的代碼,還是有點難看的。

#include <stdio.h>
#include <stdlib.h>
#include 
<string.h> #include <stdbool.h> #include "linkStack.h" bool isoperator(char op) { switch (op) { case +: case -: case *: case /: case (: return 1; default: return 0; } } int priority(char op) { switch (op) { case (
: return 0; case +: case -: return 1; case *: case /: return 2; default: return -1; } } void handle(char *s) { linkStack* stack = linkStack_Create(); int len = strlen(s); for(int i=0; i<len; ++i) { if(isoperator(s[i])) {
//如果棧為空或者是操作符為‘(‘就直接進棧了
if(linkStack_Size(stack)==0 || s[i] == () { linkStack_Push(stack,&s[i]); continue; }
//優先級的判斷
if(priority(s[i]) >= priority(*((char*)linkStack_Top(stack)))) { linkStack_Push(stack,&s[i]); }else { printf("%c", *((char*)linkStack_Pop(stack))); linkStack_Push(stack,&s[i]); } }//準備出棧了 else if(s[i] == )) { while(true) { char tmp = *((char*)linkStack_Pop(stack)); if(tmp == () break; printf("%c", tmp); } } else { printf("%c",s[i]); } }//將棧中的所有元素全部投彈出去 while(linkStack_Size(stack) > 0) { printf("%c", *((char*)linkStack_Pop(stack))); } } int main() { char mid_expre[] = "8+(3-1)*5"; handle(mid_expre); return 0; }
//後續操作,將後綴表達式進行計算也是借助於棧的利用,不過就比較簡單了相對來講。

中綴表達式轉換成為後綴表達式