簡體   English   中英

我已經編寫了這段代碼來使用 CPP 中的堆棧將中綴表達式轉換為后綴表達式

[英]I have written this code to convert an infix expression to a postfix expression using Stacks in CPP

#include<bits/stdc++.h>
using namespace std;

int prec(char c){
    if(c=='^'){
        return 3;
    }else if(c=='*' || c=='/'){
        return 2;
    }else if(c=='+' || c=='-'){
        return 1;
    }

    return -1;
}

string infixToPostfix(string );

int main(){
    string s = "(a-b/c)*(a/k-l)";

    cout<<infixToPostfix(s);

    return 0;
}

string infixToPostfix(string s){
    stack<char> st;
    string res = "";

    for(int i=0;i<s.length();i++){
        if((s[i]>='a' && s[i]<='z') || (s[i]>='A' && s[i]<='Z')){
            res+=s[i];
        }else if(s[i]=='('){
            st.push(s[i]);
        }else if(s[i]==')'){
            while((!st.empty()) && st.top()!='('){
                res+=st.top();
                st.pop();
            }
            if(!st.empty()){
                st.pop();
            }
        }else{
            while((!st.empty()) && prec(st.top())>prec(s[i])){
                res+=st.top();
                st.pop();
            }
            st.push(s[i]);
        }

        while(!st.empty()){
            res+=st.top();
            st.pop();
        }

    }
        return res;
}

如您所見,我正在嘗試將中綴表示法轉換為后綴表示法,但 output 沒有按預期出現。 我什至找不到任何語法錯誤,所以很有可能存在一些邏輯錯誤。

預期 Output:

abc/-ak/l-*

實際 Output:

(a-b/c*(a/k-l

我已經把我的大腦吹了起來,試圖找到錯誤,但我仍然沒有。 請幫我解決問題。

定義兩個優先級表,當它們在堆棧外時稱為outstack for operator,當它們在堆棧內時稱為instack for operator。

如果任何運算符是從左到右關聯的,則將優先級從outstack增加到instack 如果從右到左降低優先級。

操作 出棧前 入棧前
+ - 1 2
* / 3 4
^ 6 5
( 7 0
) 0 X

下面的程序使用此邏輯將中綴表達式轉換為后綴表達式。

#include <iostream>
#include <string>
#include <stack>
#include <map>
#include <vector>

// For left to right associative operator, precedence increase from out to in
// For right to left associative operator (like ^), precedence decrease from out to in

// Outside stack precedence
std::map<char, int> precedenceOutStack {
    {'(', 7}, 
    {')', 0},
    {'*', 3}, 
    {'/', 3},
    {'+', 1}, 
    {'-', 1},
    {'^', 6},
};

// Inside stack precedence
std::map<char, int> precedenceInStack {
    {'(', 0}, 
    {'*', 4}, 
    {'/', 4},
    {'+', 2}, 
    {'-', 2},
    {'^', 5},
};

int getOutPrecedence(char c) {
    if(precedenceOutStack.count(c) > 0) {
        return precedenceOutStack[c];
    } else {
        return 0;
    }
}

int getInPrecedence(char c) {
    if(precedenceInStack.count(c) > 0) {
        return precedenceInStack[c];
    } else {
        return 0;
    }
}

std::string infixToPostfix(std::string infix) {
    std::string postfix {};
    std::stack<char> stk;

    size_t i {};
    // loop through the input string
    while(infix[i]) {
        // if its an operand add it to postfix
        if(std::isalpha(infix[i])) {
            postfix.push_back(infix[i++]);
        } else {
            if(!stk.empty()) {
                auto outPrec = getOutPrecedence(infix[i]);
                auto inPrec = getInPrecedence(stk.top());

                // check the out precedence of input char with in precedence of stack top
                // if its greater push the operator to stack
                if( outPrec > inPrec ) {
                    stk.push(infix[i++]);
                }
                // else if it is less, append the operator from top of stack to postfix
                else if(outPrec < inPrec ) {
                    postfix.push_back(stk.top());
                    stk.pop();    
                }
                // only '(' and ')' has equal out and in precedence, ignore them 
                else if(outPrec == inPrec) {
                    stk.pop();
                    ++i;
                }
            } else {
                stk.push(infix[i++]);
            }
        }
    }

    // pop out remaining opreator from the stack and append them to postfix
    while(!stk.empty()) {
        postfix.push_back(stk.top());
        stk.pop();
    }
    return postfix;
}

int main()
{
    std::vector<std::string> inputs {
        "(a-b/c)*(a/k-l)"  // abc/-ak/l-*
    };

    for(const auto& s : inputs) {
        std::cout << "Infix: " << s << " -- ";
        std::cout << infixToPostfix(s) << std::endl;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM