給定一個中綴表達式(運算元為個位數,運算符僅含 + - * / 及括號),請將其轉換為後綴表達式(逆波蘭表示法)。測試資料組數 T < 10,每行表達式長度 ≤ 1000,保證合法且無負數。
(,直接壓入運算符棧;),彈出棧頂運算符並輸出,直到遇到左括號(左括號僅彈出不輸出);+ - * /:
* / 優先級高於 + -#include <stdio.h>
#include <string.h>
#define MAX_LEN 1000
int main(void) {
int T;
scanf("%d", &T);
while (T--) {
char infix[MAX_LEN + 1];
scanf("%s", infix);
char opStack[MAX_LEN];
int top = -1; // 運算符棧頂指標
char postfix[MAX_LEN * 2]; // 後綴結果緩衝
int pIdx = 0; // 後綴串索引
for (int i = 0; infix[i]; ++i) {
char ch = infix[i];
if (ch >= '0' && ch <= '9') {
postfix[pIdx++] = ch; // 運算元直接輸出
} else if (ch == '(') {
opStack[++top] = ch; // 左括號入棧
} else if (ch == ')') {
while (top >= 0 && opStack[top] != '(') {
postfix[pIdx++] = opStack[top--]; // 彈出至左括號
}
if (top >= 0) --top; // 丟棄左括號
} else { // 運算符 + - * /
while (top >= 0 && opStack[top] != '(') {
char topOp = opStack[top];
// 若棧頂優先級 >= 當前,則彈出
if ((topOp == '*' || topOp == '/') ||
(ch == '+' || ch == '-')) {
postfix[pIdx++] = opStack[top--];
} else break;
}
opStack[++top] = ch; // 當前運算符入棧
}
}
while (top >= 0) { // 清空剩餘運算符
postfix[pIdx++] = opStack[top--];
}
postfix[pIdx] = '\0';
puts(postfix);
}
return 0;
}
| 輸入 | 輸出 |
|---|---|
2 | 12+ |
precedence(char op) 函式提高可讀性。後綴表達式便於機器求值,只需一個運算元棧即可完成計算,是編譯器、解析器的核心基礎。