生活随笔
收集整理的這篇文章主要介紹了
栈的应用--中序表达式转后序表达式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
棧的應用--中序表達式轉后序表達式
infix : a+b*c+(d*e+f)*g
postfix : abc*+de*f+g*+
有以下四種情況:
操作數->直接輸出操作符->將棧頂輸出,直到棧頂優(yōu)先級小于該操作符,最后把該操作符壓入棧'(' ->入棧')' ->將棧中在'('之后的操作符全部輸出#include <iostream>
#include <stack>
#include <map>
#include <string>using namespace std;int main() {stack<char> op;// 規(guī)定優(yōu)先級map<char, int> mymap;mymap['+'] = 1;mymap['*'] = 2;string infix = "a+b*c+(d*e+f)*g";string postfix = "";for (int i = 0; i < infix.length(); i++) {// 操作數->直接輸出if (infix[i] >= 'a' && infix[i] <= 'z') {postfix += infix[i];} else if (infix[i] == '(') {// '(' ->入棧op.push(infix[i]);} else if (infix[i] == ')') {// ')' ->將棧中在'('之后的操作符全部輸出while (op.top() != '(') {postfix += op.top();op.pop();}// 將'('彈出op.pop();} else {// 操作符->將棧頂輸出,直到棧頂優(yōu)先級小于該操作符,最后把該操作符壓入棧while (!op.empty() && mymap[op.top()] >= mymap[infix[i]]) {postfix += op.top();op.pop();}op.push(infix[i]);}}// 將棧中剩余的操作符輸出while (!op.empty()) {postfix += op.top();op.pop();}cout << postfix << endl;return 0;
}
轉載于:https://www.cnblogs.com/bgmind/p/3989808.html
新人創(chuàng)作打卡挑戰(zhàn)賽發(fā)博客就能抽獎!定制產品紅包拿不停!
總結
以上是生活随笔為你收集整理的栈的应用--中序表达式转后序表达式的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。