C++ 中的字首轉字尾轉換
在此問題中,給出了一個字首表示式。我們的任務是列印該表示式的字尾轉換。
字首表示式是運算子位於運算元之前的表示式。
例如:+AB。
字尾表示式是運算子位於表示式中運算元之後的表示式。
例如:AB/
不要將字首轉換為字尾時涉及轉換為中綴。
我們舉一個例子來理解這個問題,
Input: /+XY+NM Output: XY+NM+/ Explanation: infix -> (X+Y)/(N+M)
為了解決此問題,我們首先以相反的順序遍歷整個字尾表示式。並且,我們將使用堆疊資料結構來進行我們的處理。對於遍歷中找到的元素情況,執行以下操作
情況:如果符號是運算元 -> 將元素壓入堆疊中。
情況:如果符號是運算子 -> 從堆疊中彈出 2*,然後將運算元 - 運算元 - 運算子序列壓入。
顯示我們演算法實現的程式
示例
#include <iostream>
#include <stack>
using namespace std;
bool isOperator(char x) {
switch (x) {
case '+':
case '-':
case '/':
case '*':
return true;
}
return false;
}
string convertToPostfix(string prefix) {
stack<string> expression;
int length = prefix.size();
for (int i = length - 1; i >= 0; i--) {
if (isOperator(prefix[i])) {
string op1 = expression.top();
expression.pop();
string op2 = expression.top();
expression.pop();
string temp = op1 + op2 + prefix[i];
expression.push(temp);
}
else
expression.push(string(1, prefix[i]));
}
return expression.top();
}
int main() {
string prefix = "*-AB/+CD*XY";
cout<<"Prefix expression : "<<prefix<<endl;
cout<<"Postfix expression : "<<convertToPostfix(prefix);
return 0;
}輸出
Prefix expression : *-AB/+CD*XY Postfix expression : AB-CD+XY*/*
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP