豬八戒做網(wǎng)站怎么樣打開百度一下的網(wǎng)址
解法:直接給算法
創(chuàng)建一個棧和一個空的后綴表達式字符串。
遍歷中綴表達式中的每個字符。
如果當前字符是操作數(shù),直接將其添加到后綴表達式字符串中。
如果當前字符是操作符,需要將其與棧頂?shù)牟僮鞣M行比較:
如果棧為空,或者棧頂操作符是左括號'(',則將當前操作符壓入棧中。
如果當前操作符的優(yōu)先級大于棧頂操作符的優(yōu)先級,將當前操作符壓入棧中。
如果當前操作符的優(yōu)先級小于等于棧頂操作符的優(yōu)先級,將棧頂操作符彈出并添加到后綴表達式字符串中,然后繼續(xù)比較當前操作符與新的棧頂操作符,直到符合壓入條件。
如果當前字符是'(',將其壓入棧中。
如果當前字符是')',需要將棧中的操作符彈出并添加到后綴表達式字符串中,直到遇到左括號為止。將左括號彈出,但不添加到后綴表達式字符串中。
遍歷完所有字符后,將棧中剩余的操作符彈出并添加到后綴表達式字符串中。
返回后綴表達式字符串。
原則就是:有括號先算括號里的,先乘除(優(yōu)先級2),再加減(優(yōu)先級1)
#include<iostream>
#include<string>
#include<stack>
using namespace std;bool isop(char c) {if (c == '+' || c == '-' || c == '*' || c == '/') {return true;}else return false;
}
int jibie(char op) {if (op == '+' || op == '-') {return 1;}else if (op == '*' || op == '/') {return 2;}return 0;
}
string trans(string s) {string p;stack<char> sk;for (int i = 0; i < s.size(); i++) {char c = s[i];if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9') {p += c;}else if (isop(c)) {while (!sk.empty() && jibie(sk.top()) >= jibie(c)) {p += sk.top();sk.pop();}sk.push(c);}else if (c=='(') {sk.push(c);}else if (c == ')') {while (!sk.empty() && sk.top() != '(') {p += sk.top();sk.pop();}sk.pop();}}while (!sk.empty()) {p += sk.top();sk.pop();}return p;
}
int main() {string str;cin >> str;cout << trans(str);return 0;
}