資料結構 用CorC++

輸入一個運算式(元) 用中置轉成後置 就例如:

輸入 2*3+5*3 中置

輸出 23*53*+ 後置

變成這樣

用C或C++都可 有人能幫我解答嗎??

*=運算子 2=運算元

1 Answer

Rating
  • 小白
    Lv 5
    1 decade ago
    Favorite Answer

    #include <iostream>

    using namespace std;

    int postfix(char*);

    int priority(char);

    void main(){

    char input[100];

    cout << "please input :" ;

    cin >> input;

    postfix(input);

    system("pause");

    }

    int postfix(char* infix) {

    int i = 0, top = 0;

    char stack[80] = {'\0'};

    char op;

    while(1) {

    op = infix[i];

    switch(op) {

    case '\0':

    while(top > 0){

    cout << stack[top];

    top--;

    }

    cout<<endl;

    return 0;

    case '(':

    if(top < (sizeof(stack) / sizeof(char))) {

    top++;

    stack[top] = op;

    }

    break;

    case '+':

    case '-':

    case '*':

    case '/':

    while(priority(stack[top]) >= priority(op)) {

    cout << stack[top];

    top--;

    }

    if(top < (sizeof(stack) / sizeof(char))) {

    top++;

    stack[top] = op;

    }

    break;

    case ')':

    while(stack[top] != '(') {

    cout << stack[top];

    top--;

    }

    top--;

    break;

    default:

    cout << op;

    break;

    }//switch

    i++;

    }//while

    }//int postfix(char* infix) {

    int priority(char op) {

    int p;

    switch(op) {

    case '+':

    case '-':

    p = 1;

    break;

    case '*':

    case '/':

    p = 2;

    break;

    default:

    p = 0;

    break;

    } //switch

    return p;

    }

    Source(s): 自己
Still have questions? Get your answers by asking now.