infix to postfix
#include <stdio.h>
#include <ctype.h>
#define MAX 20
void infixToPostfix(char[], int);
int compare(char, char);
char infixPriority[9] = { '#', ')', '+', '-', '*', '/', '^', ' ', '(' };
char stackPriority[8] = { '#', '(', '+', '-', '*', '/', '^', ' ' };
int main()
{
char infixQ[MAX];
int rear = -1;
printf("*********************************\n");
printf(" -- Usable operator --\n");
printf(" ^: Exponentiation\n");
printf(" *: Multiply /: Divide\n");
printf(" +: Add -: Subtraction\n");
printf(" (: Left Brace ): Right Brace\n");
printf("*********************************\n");
printf("Please enter infix expression: ");
while (infixQ[rear] != '\n')
infixQ[++rear] = getchar();
infixQ[rear] = '#';
printf("Postfix expression: ");
infixToPostfix(infixQ, rear);
printf("\n");
return 0;
}
int compare(char stackO, char infixO)
{
int indexS = 0, indexI = 0;
while (stackPriority[indexS] != stackO)
indexS++;
while (infixPriority[indexI] != infixO)
indexI++;
if ((stackO == '{' || stackO == '[') && (infixO == '}' || infixO == ']')) {
return 0;
}
return indexS / 2 >= indexI / 2 ? 1 : 0;
}
void infixToPostfix(char infixQ[], int rear)
{
int top = 0, ctr;
char stackT[MAX];
stackT[top] = '#';
for (ctr = 0; ctr <= rear; ctr++) {
switch (infixQ[ctr]) {
case ')':
while (stackT[top] != '(')
printf("%c", stackT[top--]);
top--;
break;
case '#':
while (stackT[top] != '#')
printf("%c", stackT[top--]);
break;
case '(':
case '^':
case '*':
case '/':
case '+':
case '-':
while (compare(stackT[top], infixQ[ctr]))
printf("%c", stackT[top--]);
stackT[++top] = infixQ[ctr];
break;
default:
if (isalpha(infixQ[ctr]) || isdigit(infixQ[ctr])) {
printf("%c", infixQ[ctr]);
}
break;
}
}
}
solution
在中序運算是佇列以及堆疊裡都存放著#符號,用來判斷是否已經到達了底端,接著通過判斷一個一個字元,來處理不一樣的事情,假如遇到右括號,就在堆疊裡尋找直到遇到左括號並彈出,如果遇到#就把堆疊裡剩下的運算子給彈出,但如果是遇到+、-、*、/、^,就先比較堆疊裡的優先權是否大於要加入的運算子的優先權,最後判斷是否為數字或字母就印出