新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
C中怎么將中綴表達式轉(zhuǎn)換為后綴表達式(中綴表達式轉(zhuǎn)后綴表達式c語言)
在C語言中,將中綴表達式轉(zhuǎn)換為后綴表達式(逆波蘭表示法)可以通過以下步驟實現(xiàn):

競秀網(wǎng)站建設公司創(chuàng)新互聯(lián)公司,競秀網(wǎng)站設計制作,有大型網(wǎng)站制作公司豐富經(jīng)驗。已為競秀超過千家提供企業(yè)網(wǎng)站建設服務。企業(yè)網(wǎng)站搭建\成都外貿(mào)網(wǎng)站建設公司要多少錢,請找那個售后服務好的競秀做網(wǎng)站的公司定做!
1、創(chuàng)建一個棧用于存儲運算符,并創(chuàng)建一個字符串用于存儲后綴表達式。
2、從左到右掃描中綴表達式。
3、如果遇到操作數(shù),將其添加到后綴表達式。
4、如果遇到運算符,則處理棧頂?shù)倪\算符,直到棧為空或者棧頂?shù)倪\算符優(yōu)先級低于當前運算符,然后將當前運算符壓入棧。
5、如果遇到左括號,將其壓入棧。
6、如果遇到右括號,處理棧頂?shù)倪\算符,直到遇到左括號為止,然后彈出左括號。
7、重復步驟26,直到掃描完中綴表達式。
8、處理棧中剩余的運算符,將其添加到后綴表達式。
以下是一個簡單的C語言實現(xiàn):
#include#include #include #include int precedence(char op) { if (op == '+' || op == '') return 1; if (op == '*' || op == '/') return 2; return 0; } void infixToPostfix(char *infix, char *postfix) { int i, j = 0; char stack[strlen(infix)]; int top = 1; for (i = 0; i < strlen(infix); i++) { if (isalnum(infix[i])) { postfix[j++] = infix[i]; } else if (infix[i] == '(') { stack[++top] = infix[i]; } else if (infix[i] == ')') { while (top != 1 && stack[top] != '(') { postfix[j++] = stack[top]; } top; } else { while (top != 1 && precedence(stack[top]) >= precedence(infix[i])) { postfix[j++] = stack[top]; } stack[++top] = infix[i]; } } while (top != 1) { postfix[j++] = stack[top]; } postfix[j] = '\0'; } int main() { char infix[] = "a+b*(c^de)^(f+g*h)i"; char postfix[strlen(infix)]; infixToPostfix(infix, postfix); printf("Infix expression: %s ", infix); printf("Postfix expression: %s ", postfix); return 0; }
這個程序?qū)⒅芯Y表達式 "a+b*(c^de)^(f+g*h)i" 轉(zhuǎn)換為后綴表達式 "abcd^efgh*+^*+i"。
新聞名稱:C中怎么將中綴表達式轉(zhuǎn)換為后綴表達式(中綴表達式轉(zhuǎn)后綴表達式c語言)
本文來源:http://www.5511xx.com/article/cocgsoj.html


咨詢
建站咨詢
